题目
这道题很简单,也是我写的第二遍。之所以再写一遍,而且使用bfs和dfs两种方式进行解题,也是想要更深入地了解一下各自的特点。
宽度优先搜索(bfs)与深度优先搜索(dfs)一样,都会生成所有能够遍历到的状态,因此需要对所有状态进行处理时使用宽度优先搜索也是可以的。但是递归函数可以很简短地编写,而且状态的管理也更简单,所以大多数情况下还是用深度优先搜索实现。反之,在求取最短路时深度优先搜索需要反复经过同样的状态,所以此时还是使用宽度优先搜索为好。
宽度优先搜索会把状态逐个加入队列,因此通常需要与状态数成正比的内存空间。反之,深度优先搜索是与最大的递归深度成正比的。一般与状态数,递归的深度并不会太大,所以可以认为深度优先搜索更加节省空间。
dfs
#include <cstdio>
#include <map>
#include <cstring>
using namespace std;
typedef pair<int, int> P;
P start;
const int maxn=22;
char maze[maxn][maxn];
bool vis[maxn][maxn];
int w, h, ans=0;
int fx[4]={-1, 1, 0, 0}, fy[4]={0, 0, -1, 1};
bool judge(int x, int y){
if(vis[x][y])
return false;
if(maze[x][y]=='#')
return false;
if(x>=h || x<0 || y>=w || y<0)
return false;
return true;
}
void dfs(P u){
vis[u.first][u.second]=true;
ans+=1;
for(int i=0; i<4; i++){
int newx=u.first+fx[i];
int newy=u.second+fy[i];
P temp;
if(judge(newx, newy)){
temp.first=newx, temp.second=newy;
dfs(temp);
}
}
}
int main()
{
while(scanf("%d%d", &w, &h)!=EOF){
if(!w && !h)
break;
ans=0;
memset(vis, false, sizeof(vis));
getchar();
for(int i=0; i<h; i++){
for(int j=0; j<w; j++){
maze[i][j]=getchar();
if(maze[i][j]=='@')
start.first=i, start.second=j;
}
getchar();
}
dfs(start);
printf("%d\n", ans);
}
return 0;
}
对于dfs,我写的很快;对于bfs,对于我确实想了一会儿,在哪里使用数组vis来记录该点已被访问过。而且dfs确实比bfs的运行快, dfs的TIME是16MS,bfs的TIME是63MS
bfs
#include <cstdio>
#include <cstring>
#include <map>
#include <queue>
using namespace std;
const int maxn=22;
typedef pair<int, int> P;
char maze[maxn][maxn];
bool vis[maxn][maxn];
int w, h, ans=0;
int fx[4]={-1, 1, 0, 0}, fy[4]={0, 0, -1, 1};
P start;
bool judge(int x, int y){
if(vis[x][y])
return false;
if(maze[x][y]=='#')
return false;
if(x>=h || x<0 || y>=w || y<0)
return false;
return true;
}
void bfs(){
queue<P> q;
q.push(start);
vis[start.first][start.second]=true;
while(!q.empty()){
P top=q.front();
q.pop();
ans+=1;
for(int i=0; i<4; i++){
int newx=fx[i]+top.first;
int newy=fy[i]+top.second;
P temp;
if(judge(newx, newy)){
temp.first=newx, temp.second=newy;
q.push(temp);
vis[temp.first][temp.second]=true;
}
}
}
}
int main()
{
while(scanf("%d%d", &w, &h)!=EOF){
if(!w && !h)
break;
ans=0;
memset(vis, false, sizeof(vis));
getchar();
for(int i=0; i<h; i++){
for(int j=0; j<w; j++){
maze[i][j]=getchar();
if(maze[i][j]=='@')
start.first=i, start.second=j;
}
getchar();
}
bfs();
/*for(int i=0; i<h; i++){
for(int j=0; j<w; j++){
if(vis[i][j])
ans+=1;
}
}*/
printf("%d\n", ans);
}
return 0;
}