今天刚学习了广度优先搜索bfs,利用队列来维护。
首先讲初始状态加入队列,此后不断取出队首元素,判断是否满足搜索结束条件(到达终点等),若不满足,在给定的4个或8个方向进行搜索,并且要注意越界、是否已经访问、是否允许访问等约束条件,若满足,则将该点加入队列,并且改变标记距离的数组的值。当队列为空或到达终点时搜索结束。
HDU 1312 BFS裸题http://acm.hdu.edu.cn/showproblem.php?pid=1312
#include<cstdio>
#include<queue>
#define MAX 20
#define INF 100000000
using namespace std;
char maze[MAX][MAX + 1];
int cnt[MAX][MAX + 1];
int h, w;
int sx, sy;
typedef pair<int ,int> P;
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
void bfs(){
queue<P> que;
que.push(P(sx, sy));
cnt[sx][sy] = 1;
while(!que.empty()){
P p = que.front();
que.pop();
for(int i = 0;i < 4;i++){
int nx = p.first + dx[i], ny = p.second + dy[i];
if(nx >= 0 && nx < w && ny >= 0 && ny < h && maze[nx][ny] != '#' && cnt[nx][ny] == 0){
que.push(P(nx, ny));
cnt[nx][ny] = 1;
}
}
}
}
main(){
while(~scanf("%d %d",&h, &w)){
getchar();
if(h == 0 && w == 0) break;
for(int i = 0;i < w;i++){
gets(maze[i]);
}
for(int i = 0;i < w;i++){
for(int j = 0;j < h;j++){
if(maze[i][j] == '@'){
sx = i;
sy = j;
break;
}
}
}
for(int i = 0;i < w;i++){
for(int j = 0;j < h;j++){
cnt[i][j] = 0;
}
}
bfs();
int sum = 0;
for(int i = 0;i < w;i++){
for(int j = 0;j < h;j++){
sum += cnt[i][j];
}
}
printf("%d\n", sum);
}
}
“`