这是我在HDU上解决的第一道独立完成的dfs,故此一记!
这题WA了两次:
1、在写dfs()函数时将递归出口写成了if(r==0 || r==10 || c==0 || c==10)。试想怎么可能是10呢?要根据输入的行列来确定出口哇!
2、把记录遍历点的node ppp[50]开成50,试想行列最大都为10,那么走过的点很可能会超过50呀!那么回溯是就会出错啦!
详见代码注释:
#include<iostream>
using namespace std;
char graph[12][12]; //存图
bool visited[12][12]; //标志每个顶点是否被访问过
int row,col,start,count,flag; //count用来记录步数,flag记录是否存在循环
struct node //记录走过的点,以便在监测到存在循环时回溯
{
int x;
int y;
}ppp[120];
void store_graph() //初始化图
{
for(int i=1;i<=row;i++)
for(int j=1;j<=col;j++)
cin>>graph[i][j];
}
void dfs(int r,int c)
{
if(r==0 || r==row+1 || c==0 || c==col+1) //存储图范围以外的行列标志成功出来
return; //出口
else
{
if(visited[r][c]==false)
{
visited[r][c]=true;
count++;
ppp[count].x=r;
ppp[count].y=c;
if(graph[r][c]=='N')
dfs(r-1,c);
else if(graph[r][c]=='S')
dfs(r+1,c);
else if(graph[r][c]=='E')
dfs(r,c+1);
else
dfs(r,c-1);
}
else //如果访问了一个已被访问过的顶点,说明要循环了
{
flag=1; //标志存在循环
return; //出口
}
}
}
int judge_rec() //回溯,返回非循环的步数
{
int i=ppp[count].x;
int j=ppp[count].y;
int tem1,tem2;
if(graph[i][j]=='N') //寻找循环开始的位置,也即非循环进入循环的位置
{
tem1=i-1;
tem2=j;
}
else if(graph[i][j]=='S')
{
tem1=i+1;
tem2=j;
}
else if(graph[i][j]=='W')
{
tem1=i;
tem2=j-1;
}
else
{
tem1=i;
tem2=j+1;
}
int tem=0;
for(i=1;i<=count;i++) //确定非循环的步数
{
if(ppp[i].x==tem1 && ppp[i].y==tem2)
break;
else
tem++;
}
return tem;
}
int main()
{
while(cin>>row>>col>>start,row||col||start)
{
memset(visited,false,sizeof(visited)); //每次都需重设访问标志
store_graph();
count=0;
flag=0;
dfs(1,start);
if(flag==1)
{
int rec=judge_rec();
cout<<rec<<" step(s) before a loop of "<<count-rec<<" step(s)";
}
else
cout<<count<<" step(s) to exit";
cout<<endl;
}
return 0;
}
外送三组测试数据:
1 1 1
S
2 1 1
S
N
1 2 1
EW
答案分别如下:
1 step(s) to exit
0 step(s) before a loop of 2 step(s)
0 step(s) before a loop of 2 step(s)