VJ原题链接https://vjudge.net/contest/467285#problem/Ehttps://vjudge.net/contest/467285#problem/E
问题:
在这会用到 pair<int, int>(pair类型) 来记录当前步数的坐标,然后就是入队出队(队列)。
AC代码:
#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
#include<functional>
using namespace std;
typedef pair<int, int> pp;
int a[5][5], vis[5][5];//地图 和 记忆数组
struct node{
int x, y, step;
pp p[30];
};
queue<node>q;
int fx[4]= {1, -1, 0, 0}, fy[4] = {0 , 0, 1, -1};//上下左右
void bfs(){
int i = 0, j;
node n, temp;
n.x = 0; n.y = 0; n.step = 0;
n.p[n.step++] = pp(n.x, n.y); //记录当前坐标
q.push(n);
vis[n.x][n.y] = 1; //走过了哦
while(!q.empty()){
temp = q.front();q.pop();
if(temp.x == 4&&temp.y == 4){
for(i = 0; i < temp.step; i++){
cout << '(' << temp.path[i].first << ", " << temp.path[i].second << ')' << endl;
/*c语言的输出printf("(%d, %d)", (int)temp.p[i].first, (int)temp.p[i].second);
if(i != temp.step-1) printf("\n");*/
}
return ;
}
for(j = 0; j < 4; j++){
node next = temp;
next.x = temp.x + fx[j]; next.y = temp.y + fy[j];
if(!vis[next.x][next.y] && next.x >= 0 && next.y >= 0 && next.x < 5 && next.x < 5 && a[next.x][next.y] == 0){
vis[next.x][next.y] = 1;//这个地方没走过(如果走过了自然不是最快的
next.p[next.step++] = pp(next.x,next.y); //再记录
q.push(next);
}
}
}
}
int main()
{
int i, j;
for(i = 0; i < 5; i++){
for(j = 0; j < 5; j++){
cin >> a[i][j]; /*c语言的输入scanf("%d", &a[i][j]);*/
}
}
bfs();
return 0;
}