POJ 1979 Red and Black(BFS广度优先搜索)

//BFS统计可以行动的地图点数 #include<iostream> #include<cstring> #include<queue> using namespace std; char map[22][22]; bool in_queue[450];//标记是否进过队列 int ans; int X,Y; inline int xy_p(int x,int y) { return y*X + x; } inline int p_x(int p) { return p%X; } inline int p_y(int p) { return p/X; } //三个基本转换函数,二维到一维的转化 void dfs(int p,queue<int> &q)//深度优先搜索模板,从一个一维坐标开始深搜 { int P; int x = p_x(p); int y = p_y(p); //判断三件事情,是否越界?地图条件满足?是否已加入过队列? P = xy_p(x+1,y); if(x+1 < X && map[y][x+1] != '#' && !in_queue[P]) { q.push(P); in_queue[P] = 1; ans++; } P = xy_p(x-1,y); if(x-1 >= 0 && map[y][x-1] != '#' && !in_queue[P]) { q.push(P); in_queue[P] = 1; ans++; } P = xy_p(x,y+1); if(y+1 < Y && map[y+1][x] != '#' && !in_queue[P]) { q.push(P); in_queue[P] = 1; ans++; } P = xy_p(x,y-1); if(y-1 >= 0 && map[y-1][x] != '#' && !in_queue[P]) { q.push(P); in_queue[P] = 1; ans++; } q.pop(); } int main() { //freopen("in.txt","r",stdin); while(scanf("%d%d",&X,&Y))//X Y为地图边界 { if(X == 0) break; ans = 1; memset(in_queue,0,sizeof(in_queue)); queue<int> q; for(int i = 0;i < Y;++i) { scanf("%s",map[i]); for(int j = 0;j < strlen(map[i]);++j) { if(map[i][j] == '@') { q.push(xy_p(j,i));//插入起点 in_queue[xy_p(j,i)] = 1; } } } while(!q.empty()) { dfs(q.front(),q); } printf("%d/n",ans); } return 0; }  

你可能感兴趣的:(POJ 1979 Red and Black(BFS广度优先搜索))