很简单的搜索,只要广搜就可以了,然后就是记录搜索地址,最后我竟然又用了一遍DFS(),求出了最后的路径。
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
宽搜后的结果,然后再DFS回溯求返回路径就可以
1 0 7 8 0
2 0 6 0 8
3 4 5 6 7
4 0 0 0 8
5 6 7 0 9
最近第一次写搜索~~勿喷:
#include<stdio.h>
#include<string.h>
#include<queue>
#include<stack>
#include<iostream>
using namespace std;
struct node{
int x,y,step;
node(){}
node(int a,int b,int c):x(a),y(b),step(c){}
}tmp;
int dx[6]={0,0,0,1,-1};
int dy[6]={0,1,-1,0,0};
int point[7][7];
int rec[7][7];
queue <struct node> que;
void dfs(node t){ //回溯算法
for(int i=1;i<=4;i++){
int x=t.x+dx[i],y=t.y+dy[i];
if(x<1||x>5||y<1||y>5)continue;
if(rec[x][y]==t.step-1&&rec[x][y]>=1){
dfs( node(x,y,rec[x][y]) );
printf("(%d, %d)\n",x-1,y-1);
}
}
}
int main()
{
while(scanf("%d",&point[1][1])!=EOF){
int step=1;
memset(point,0,sizeof(point));
memset(rec,0,sizeof(rec));
for(int i=2;i<=5;i++)
scanf("%d",&point[1][i]);
for(int i=2;i<=5;i++)
for(int j=1;j<=5;j++)
scanf("%d",&point[i][j]);
while(que.empty()!=true)que.pop(); //将队列元素全部清除
rec[1][1]=step;
que.push(node(1,1,1));
while(que.empty()!=true){ //宽搜
tmp=que.front();
que.pop();
for(int i=1;i<=4;i++){
int x=tmp.x+dx[i],y=tmp.y+dy[i];
if(point[x][y]==1)continue; //不能撞墙
if(x<1||x>5||y<1||y>5)continue; //界限判定
if(rec[x][y]!=0)continue; //是否经过
rec[x][y]=tmp.step+1;
if(x==5&&y==5)goto end;
//cout<<x<<" "<<y<<" "<<rec[x][y]<<endl;
que.push(node(x,y,rec[x][y]) );
}
}
end:;
dfs(node(5,5,rec[5][5]));
printf("(%d, %d)\n",4,4);
}
}