トピックが投稿されました:
最短パスの長さを見つけるトピックと比較して、このトピックはすべての最短パスポイントの出力を必要とするため、少し難しいかもしれません。
アイデア:x、y座標で構造を定義します。トラバースポイントとポイントの親ポイント(最後の状態を意味します)。たとえば、パスは(0,0)->(1,1)->(2,2)であり、次にポイント(2,2)が(1,1)の場合、親ポイントのあるポイントを出力し、親ポイントのないポイントは出力しません。以下はコードです。ある特定の繰り返しトラバースを防ぐためのコードです。ポイント、訪問マークを追加
// YSJ 2020-11-1---18:05
#include<iostream>
#include<cstdio>
using namespace std;
//const int MAX = 1e6+20;
int dir_x[4]={
0,-1,1,0};//down,left,right,up
int dir_y[4]={
1,0,0,-1};
struct Node{
int x,y,pre;
}Queue[30];
int front = 0,rear = 0;
int a[8][8],visit[8][8];
void BFS(int Bx,int By,int Ex,int Ey)
{
Queue[0].x = Bx;
Queue[0].y = By;
Queue[0].pre = -1;
++rear;
visit[Bx][Bx]=1;
while(front < rear){
for(int i=0;i<4;++i){
//上 ,下 ,左,右四个方向判断
int newx = Queue[front].x + dir_x[i];
int newy = Queue[front].y + dir_y[i];
if(newx<1||newy<1||newx>5||newy>5||visit[newx][newy]||a[newx][newy]==1)
continue;
//否则,进队
Queue[rear].x = newx;
Queue[rear].y = newy;
Queue[rear].pre = front;
++rear;
visit[newx][newy] = 1;
if(newx == Ex && newy == Ey)
return;
}
++front;
}
}
void Print_Path(Node now) //下面减1的原因是我的数组下标是从1开始的,
//题目是从0开始的
{
if(now.pre==-1){
printf("(%d, %d)\n",now.x-1,now.y-1);
}else{
Print_Path(Queue[now.pre]);//这里寻求父亲点,有点并查集的味道
printf("(%d, %d)\n",now.x-1,now.y-1);
}
}
int main(void)
{
int t;
for(int i=1;i<=5;++i)
for(int j=1;j<=5;++j)
cin>>a[i][j];
BFS(1,1,5,5);
Print_Path(Queue[rear-1]);
}