题目HDU1312
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1312
在这里说一下DFS的思路吧,DFS就是递归,设num是到达砖块的数量,算法过程描述如下:
- 在出书位置令num=1,标记这个位置已经走过
- 左,上,右,下四个方向,按顺时针顺序选一个能走的方向,走一步
- 在新的位置num++,标记这个位置已经走过
- 继续前进,如果无路可走,回退到上一步,换个方向再走
- 继续以上过程,直到结束
诶图像传不上来,不传了,挺简单的,我这种笨比都能懂
AC代码:
#include<bits/stdc++.h>
using namespace std;
char room[23][23];
int dir[4][2] = {{-1,0},{0,-1},{1,0},{0,1}};//左上角的坐标是(0,0)
int wx,hy,num;//wx行,hy列,num统计可走的位置有多少
#define check(x,y)(x<wx&&x>=0&&y>=0&&y<hy)//是否在room中
struct node{
int x,y;
};
void dfs(int dx,int dy){
room[dx][dy] = '#';//标记这个位置,表示已经走过
cout<<"walk:"<<dx<<dy<<endl;//打印走过的位置
num++;
for(int i=0;i<4;i++){//左上右下顺时针dfs
int newx=dx+dir[i][0];
int newy=dy+dir[i][1];
if(check(newx,newy)&&room[newx][newy] == '`'){
dfs(newx,newy);
cout<<"back:"<<dx<<dy<<endl;
}
}
}
int main(){
int x,y,dx,dy;
while(cin>>wx>>hy){
if(wx==0&&hy==0)break;//结束
for(y=0;y<hy;y++){
for(x=0;x<wx;x++){//一次读入一行
cin>>room[x][y];
if(room[x][y] == '@'){//读入起点
dx=x;
dy=y;
}
}
}
num=0;
dfs(dx,dy);
cout<<num<<endl;
}
return 0;
}
DFS比BFS代码量少多啦!
顺便贴一下BFS的代码。会明显的发现这个模板该怎么用
重复的部分不贴了,下面上伪代码:
void bfs(int dx, int dy){
num=1;//起点也包含在砖块内
queue<node>q;//队列中放坐标点
node start,next;
start.x=dx;
start.y=dy;
q.push(start);
while(!q.empty()){
start=q.front();
q.pop();
//cout<<"out:"<<start.x<<start.y<<endl;
for(int i=0;i<4;i++){
next.x=start.x+dir[i][0];
next.y=start.y+dir[i][1];
if(check(next.x,next.y)&&room[next.x][next.y]=='`'){
room[next.x][next.y]='#';
num++;
q.push(next);
}
}
}
}