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,
};
Input
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<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
int a[6][6],book[6][6];
struct node
{
int x;
int y;
int s;
int f;
}que[100];
int main()
{
int next[4][2]={1,0,0,-1,-1,0,0,1};
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
scanf("%d",&a[i][j]);
int head=1,tail=1;
que[head].x=0;
que[head].y=0;
que[head].s=0;
que[head].f=0;
book[1][1]=1;
tail++;
int flag=0,tx,ty;
while(head<tail)
{
for(int k=0;k<=3;k++)
{
tx=que[head].x+next[k][0];
ty=que[head].y+next[k][1];
if(tx<0||tx>4||ty<0||ty>4)
continue;
if(a[tx][ty]==0&&book[tx][ty]==0)
{
book[tx][ty]=1;
que[tail].x=tx;
que[tail].y=ty;
que[tail].s=que[head].s+1;
que[tail].f=head;
tail++;
}
if(tx==4&&ty==4)
{
flag=1;
break;
}
}
if(flag==1)
break;
head++;
}
int ax[30]={0},ay[30]={0};
int z=-1;
ax[++z]=que[tail-1].x;
ay[z]=que[tail-1].y;
int sum=que[tail-1].s;
tail=tail-1;
for(int i=1;i<sum;i++)
{
tail=que[tail].f;
ax[++z]=que[tail].x;
ay[z]=que[tail].y;
}
ax[++z]=0;
ay[z]=0;
for(int j=z;j>=0;j--)
printf("(%d, %d)\n",ax[j],ay[j]);
return 0;
}