迷宫问题

#include <iostream>

typedef struct Node{
	int x,y;  //行和列
	int pre;  //前驱节点
}Queue;

const int N=8;
const int M=8;

void path(int (*map)[N+2],int ix,int iy,int ex,int ey){
	const int MaxSize=50;
	Queue q[MaxSize];
	int c_x,c_y;
	int i=0,k=0;   //i是出队列位置,k是进队列位置
	q[0].x=ix; q[0].y=iy;q[0].pre=-1;map[ix][iy]=-1;

	while(true){
		c_x=q[i].x;c_y=q[i].y;
		int l=0;
		if(c_x==ex&&c_y==ey){
			while(i>=0){
				std::cout<<"("<<q[i].x<<","<<q[i].y<<")  ";
				i=q[i].pre;
				l++;
			    if(l%6==0)
				   std::cout<<std::endl;
			}
			return;
		}

		if(map[c_x][c_y+1]==0){
			k++;q[k].x=c_x;q[k].y=c_y+1;q[k].pre=i;map[c_x][c_y+1]=-1;
		}
		if(map[c_x+1][c_y]==0){
			k++;q[k].x=c_x+1;q[k].y=c_y;q[k].pre=i;map[c_x+1][c_y]=-1;
		}
		if(map[c_x][c_y-1]==0){
			k++;q[k].x=c_x;q[k].y=c_y-1;q[k].pre=i;map[c_x][c_y-1]=-1;
		}
		if(map[c_x-1][c_y]==0){
			k++;q[k].x=c_x-1;q[k].y=c_y;q[k].pre=i;map[c_x-1][c_y]=-1;
		}
		i++;
	}
}

int main(){
	int map[M+2][N+2]={
		{1,1,1,1,1,1,1,1,1,1},
		{1,0,0,1,0,0,0,1,0,1},
		{1,0,0,1,0,0,0,1,0,1},
		{1,0,0,0,0,1,1,0,0,1},
		{1,0,1,1,1,0,0,0,0,1},
		{1,0,0,0,1,0,0,0,0,1},
		{1,0,1,0,0,0,1,0,0,1},
		{1,0,1,0,0,0,1,0,0,1},
		{1,1,0,0,0,0,0,0,0,1},
		{1,1,1,1,1,1,1,1,1,1}
	};
	path(map,1,1,8,8);
	return 1;
}

 运行结果:

(8,8)  (8,7)  (8,6)  (8,5)  (7,5)  (6,5)
(6,4)  (6,3)  (5,3)  (5,2)  (5,1)  (4,1)
(3,1)  (2,1)  (1,1) 

你可能感兴趣的:(迷宫)