题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
#include <malloc.h>
#include <stdio.h>
#include <string.h>
int map[11][11];
int visited[11][11];
int way[11*11][2];
int step=0;
int file_way(int row, int col, int i, int j)
{
if( i == row-1 && j == col-1) //到达终点
{
//记录路线
visited[i][j]=1;
way[step][0]=i;
way[step][1]=j;
return 1; //找到路线
}else if(i<0 || i>row-1 || j<0 || j>col-1 || visited[i][j]==1 || map[i][j]==1)
{
return 0;
}else{
int isfide;
visited[i][j]=1;
way[step][0]=i;
way[step++][1]=j;
isfide = file_way(row,col,i,j-1);
if(isfide) return 1;
isfide = file_way(row,col,i,j+1);
if(isfide) return 1;
isfide = file_way(row,col,i-1,j);
if(isfide) return 1;
isfide = file_way(row,col,i+1,j);
if(isfide) return 1;
}
way[step][0]=0;
way[step][1]=0;
step--;
return 0;
}
int main() {
int row, col;
while (scanf("%d %d", &row, &col) != EOF)
{ // 注意 while 处理多个 case
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
scanf("%d",&map[i][j]);
}
}
for(int i=0;i<col;i++)
{
memset(visited[i],0,sizeof(int)*col);
}
for(int i=0;i<col*row;i++)
{
memset(way[i],0,sizeof(int)*2);
}
int isfide = file_way( row, col, 0, 0);
if(isfide)
{
for(int i=0;i<=step;i++)
{
printf("(%d,%d)\n",way[i][0],way[i][1]);
}
}else printf("no way exit!\n");
}
return 0;
}