J - 迷宫问题 (DFS)

定义一个二维数组: 

int maze[5][5] = {

	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,

};


它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

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

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
struct node{
	int x,y,step;
}path[100+10][100+10];
int m,n;
int str[40][40];
int vis[40][40];
bool operator < (node a,node b){
	return a.step>b.step;
}
void print(int i, int j)
{
    if(i == 0 && j == 0)
        return;
    print(path[i][j].x, path[i][j].y); //递归打印路径
    printf("(%d, %d)\n", i, j);
}
void BFS(int x1,int y1){
	priority_queue<node>que;
	node e1,e2;
	memset(vis,0,sizeof(vis));
	e1.x=0, e1.y=0, e1.step=0;
	vis[0][0]=1;
	que.push(e1);
	while(!que.empty()){
		e1=que.top();
		que.pop();
		if(e1.x==4&&e1.y==4){
			printf("(0, 0)\n");
            print(4, 4);
			break;
		}
		vis[e1.x][e1.y]=1;
		int p[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
		for(int i=0;i<4;i++){
			e2.x=e1.x+p[i][0];
			e2.y=e1.y+p[i][1];
			if(vis[e2.x][e2.y]==1) continue;
			if(str[e2.x][e2.y]==1) continue;
			if(e2.x<0||e2.x>=5||e2.y<0||e2.y>=5) continue;
			else e2.step =e1.step +1;
			que.push(e2);
			vis[e2.x][e2.y]=1;
			path[e2.x][e2.y].x = e1.x; //存坐标//
            path[e2.x][e2.y].y = e1.y; 
		}
	}
}
int main()
{
	memset(str,0,sizeof(str));
	for(int i=0;i<5;i++){
		for(int j=0;j<5;j++){
			scanf("%d",&str[i][j]);
		}
	}
	BFS(0,0); 
return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41555192/article/details/81349937