1076迷路(ステップの最小数、出力パス)AcWing

トピックリンク:こちらをクリックし
ここに画像を挿入説明
ここに画像を挿入説明
ている壁を通って道になるために、 0 0 に設定されています 1 1 重量決意の目的を達成するように

出力パス:配列シミュレーションキュー構造、事前にそれが最後に到達したときに、配列内のキュー要素インデックスの前に記録し、再帰的なバックトラックバック出力パス。

注:彼らは最後に達するとBFS自体が既に最短プロパティが含まれているので、それが最短ルートで、出力が可能。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 1010, M = N * N;

int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};

struct node {
	int x, y, pre;          // pre记录前一个元素在队列数组中的下标
	node() {}
	node(int _x, int _y, int _p) : x(_x), y(_y), pre(_p) {}
};

int n;
int g[N][N];
int hh = 0, tt = -1;        // 队首和队尾
node q[M];                  // 数组模拟队列

void print(node t)
{
	if(t.pre == -1)
	{
	    printf("%d %d\n", t.x, t.y);
	    return;
	}
	
	print(q[t.pre]);
	
	printf("%d %d\n", t.x, t.y);
}

void bfs()
{
    q[++tt] = node(0, 0, -1);
    g[0][0] = 1;
    
    while(hh <= tt)
    {
        node t = q[hh];                                     // 取队首元素
        
        for(int i = 0; i < 4; ++i)
        {
            int nx = t.x + dx[i], ny = t.y + dy[i];
            
            if(nx < 0 || nx >= n || ny < 0 || ny >= n)  continue;
            if(g[nx][ny] == 1)  continue;
            
            q[++tt] = node(nx, ny, hh);
            g[nx][ny] = 1;
            
            if(nx == n - 1 && ny ==  n - 1)   return;     // 到达终点
        }
        
        hh++;                                             // 删队首元素
    }
}

int main()
{
    scanf("%d", &n);
    
    for(int i = 0; i < n; ++i)
        for(int j = 0; j < n; ++j)
            scanf("%d", &g[i][j]);
    
    bfs();
    
    print(q[tt]);
    
    return 0;
}
844元記事公開 ウォンの賞賛135 ビュー150,000 +を

おすすめ

転載: blog.csdn.net/qq_42815188/article/details/105064238