题目大意:一个5X5的矩阵,0表示可以走,1表示不能走,输出从(0,0)到(4,4)的最短走法
解题思路:首先想到是广搜,用队列实现,从(0,0)开始,第一次遇到(4,4)就停止搜索,因为要输出走法,就要不断记录前一个点,不断自身递归调用,直到输出第一个点,因为第一个点的pre为-1,所以要手动输出,最后一个点还没有加入队列,也需要手动输出
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <string>
#include <queue>
#include <vector>
#include <list>
#include <stack>
#include <map>
#include <set>
using namespace std;
const int dir[4][2] = {{-1,0},{1,0},{0,1},{0,-1}};
struct Node
{
int x,y,pre;
}q[100];
int head = 0,rear = 1;
int a[5][5];
void print(int i)
{
if(q[i].pre != -1)
{
print(q[i].pre);
printf("(%d, %d)\n",q[i].x,q[i].y);
}
}
void bfs(int x1,int y1)
{
q[head].x = x1;
q[head].y = y1;
q[head].pre = -1;
while(head < rear)
{
for(int i = 0; i < 4; i++)
{
int xx = q[head].x+dir[i][0];
int yy = q[head].y+dir[i][1];
if(xx<0 || xx>4 || yy<0 || yy>4 || a[xx][yy]) continue;
else
{
a[xx][yy] = 1;
q[rear].x = xx;
q[rear].y = yy;
q[rear].pre = head;
rear++;//入队
}
if(xx==4 && yy==4) print(head);
}
head++;//出队
}
}
int main()
{
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++)
scanf("%d",&a[i][j]);
printf("(0, 0)\n");
bfs(0,0);
printf("(4, 4)\n");
return 0;
}