现在的位置: 首页 > 综合 > 正文

HDOJ–1312–Red and Black【DFS】

2018年01月12日 ⁄ 综合 ⁄ 共 1009字 ⁄ 字号 评论关闭

链接:http://acm.hdu.edu.cn/showproblem.php?pid=1312

简单的DFS

#include<cstring>
#include<string>
#include<fstream>
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<cctype>
#include<algorithm>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<ctime>
#include<cstdlib>
#include<functional>
#include<cmath>
using namespace std;
#define PI acos(-1.0)
#define MAXN 100100
#define eps 1e-7
#define INF 0x7FFFFFFF
#define long long ll;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1

char a[30][30];
int vis[30][30];
int dir[4][2] = {1,0,-1,0,0,1,0,-1};
int n,m,step;
bool cango(int xx,int yy){
    if(xx>=0&&xx<n&&yy>=0&&yy<m)    return true;
    return false;
}
int dfs(int x,int y){
    vis[x][y] = 1;
    step++;
    int i;
    for(i=0;i<4;i++){
        int xx = x + dir[i][0];
        int yy = y + dir[i][1];
        if(a[xx][yy]=='.'&&cango(xx,yy)&&!vis[xx][yy]){
            dfs(xx,yy);
        }
    }
}
int main(){
    int i,j,px,py;
    while(scanf("%d%d",&m,&n),m&&n){
        memset(vis,0,sizeof(vis));
        step = 0;
        for(i=0;i<n;i++){
            scanf("%s",a[i]);
            for(j=0;j<m;j++){
                if(a[i][j]=='@'){
                    px = i;
                    py = j;
                }
            }
        }
        vis[px][py] = 1;
        dfs(px,py);
        printf("%d\n",step);
    }
    return 0;
}

抱歉!评论已关闭.