#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
int Maze[SIZE][SIZE]={{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}};//迷宫
int temp_x[101]={};
int temp_y[101]={};
int path_x[101]={};
int path_y[101]={};
int DX[4] ={-1,0,1,0};//坐标移动 上/右/下/左
int DY[4] ={0,1,0,-1};
int count;
int countNUM = 25;
int z=0;
//int countNUM_cishu =0;
bool findPath = false;//判断是否找到路径
void print(){//打印路径
for(int i=0;i<SIZE;i++){
for(int j=0;j<SIZE;j++){
if (Maze[i][j]== 2)
printf("A");
else
printf("*");
}
printf("\n");
}
}
int lujing_length(){
for(int i=0;i<SIZE;i++){
for(int j=0;j<SIZE;j++){
if (Maze[i][j]== 2)
count++;
}
}
return count;
}
void DFS(int x,int y){
if((x==(SIZE-1))&&(y==(SIZE-1))){//路径找到出口,迭代停止
findPath = true;
//print();
count=lujing_length();
if(count<countNUM){
countNUM =count;
for(int i=0;i<countNUM;i++){
path_x[i]=temp_x[i];
path_y[i]=temp_y[i];
}
}
//printf("%d\n",countNUM);
count = 0;
return;
}
for(int i=0;i<4;i++){//x,y在4个方向的位移
int NX = x+DX[i];
int NY = y+DY[i];
if((NX>=0&&NX<5)&&(NY>=0&&NY<5)&&(Maze[NX][NY] == 0)){//不出界,并路可走
int temp = Maze[NX][NY];
temp_x[z]=NX;
temp_y[z]=NY;
z++;
Maze[NX][NY]=2;//记录所走过的路径
DFS(NX,NY);
z=z-1;
Maze[NX][NY] = temp;//??
}
}
}
void main(){
DFS(0,0);
//printf("%d\n",findPath);
//print();
//printf("%d\n",countNUM);
printf("(%d, %d)\n",0,0);
for(int i=0;i<countNUM;i++){
printf("(%d, %d)\n",path_x[i],path_y[i]);
//printf("\n");
}
}
POJ3984 迷宫问题
最新推荐文章于 2020-03-18 16:55:22 发布