描述
这有一个迷宫,有0~8行和0~8列:
1,1,1,1,1,1,1,1,1
1,0,0,1,0,0,1,0,1
1,0,0,1,1,0,0,0,1
1,0,1,0,1,1,0,1,1
1,0,0,0,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,0,0,0,1
1,1,1,1,1,1,1,1,1
0表示道路,1表示墙。
现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?
(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)
-
输入
-
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
输出
- 输出最少走几步。
-
1)深度优先搜索
#include <iostream>
using namespace std;
int n,a,b,c,d;//分别表示起点的行、列,终点的行、列
int ans;
int Maze[9][9]={1,1,1,1,1,1,1,1,1,
1,0,0,1,0,0,1,0,1,
1,0,0,1,1,0,0,0,1,
1,0,1,0,1,1,0,1,1,
1,0,0,0,0,1,0,0,1,
1,1,0,1,0,1,0,0,1,
1,1,0,1,0,1,0,0,1,
1,1,0,1,0,0,0,0,1,
1,1,1,1,1,1,1,1,1};
void dfs(int CurX,int CurY,int step){
if(CurX==c&&CurY==d){
ans=ans<step?ans:step;
return;
}
if(Maze[CurX][CurY]||CurX<0||CurX==9||CurY<0||CurY==9){
return;
}
Maze[CurX][CurY]=1;
step++;
dfs(CurX+1,CurY,step);
dfs(CurX-1,CurY,step);
dfs(CurX,CurY+1,step);
dfs(CurX,CurY-1,step);
Maze[CurX][CurY]=0;
}
int main(){
int A[9][9]={1};//标记最短路径
int i,j,k;
cin>>n;
while(n--){
ans=99999999;
cin>>a>>b>>c>>d;
dfs(a,b,0);
cout<<ans<<endl;
}
return 0;
}
2)广度优先搜索,找到一条路径即为最终路径
#include <iostream>
#include <queue>
using namespace std;
int n,a,b,c,d;//分别表示起点的行、列,终点的行、列
int i;
int Maze[9][9]={1,1,1,1,1,1,1,1,1,
1,0,0,1,0,0,1,0,1,
1,0,0,1,1,0,0,0,1,
1,0,1,0,1,1,0,1,1,
1,0,0,0,0,1,0,0,1,
1,1,0,1,0,1,0,0,1,
1,1,0,1,0,1,0,0,1,
1,1,0,1,0,0,0,0,1,
1,1,1,1,1,1,1,1,1};
int visit[9][9]={0};
struct Point {
int x;
int y;
int step;
};
//int move[4][2]={{1,0,-1,0},{0,1,0,-1}};
struct _smove{
int x;
int y;
}Move[4];
void bfs(int a,int b){
Point cur,nex;//当前点和后来点
queue<Point> NextPoint;//后来点的集合
Move[0].x=1,Move[0].y=0;
Move[1].x=0,Move[1].y=-1;
Move[2].x=-1,Move[1].y=0;
Move[3].x=0,Move[3].y=1;
cur.x=a,cur.y=b,cur.step=0;
NextPoint.push(cur);
visit[a][b]=1;
while(!NextPoint.empty()){
cur=NextPoint.front();
NextPoint.pop();
if(cur.x==c&&cur.y==d){
cout<<cur.step<<endl;
return;
}
for(i=0;i<4;i++){
nex=cur;
nex.x=cur.x+Move[i].x;
nex.y=cur.y+Move[i].y;
if(!Maze[nex.x][nex.y]&&!visit[nex.x][nex.y]&&nex.x>-1&&nex.x<9&&nex.y>-1&&nex.y<9){
nex.step++;
visit[nex.x][nex.y]=1;
NextPoint.push(nex);
}
}
}
visit[a][b]=0;
}
int main(){
int k,j;
cin>>n;
while(n--){
for(k=0;k<9;k++)
for(j=0;j<9;j++)
visit[k][j]=0;
cin>>a>>b>>c>>d;
bfs(a,b);
}
system("pause");
return 0;
}