AcWing 1076. maze (minimum number of steps, the output path)

Topic links: Click here
Here Insert Picture Description
Here Insert Picture Description
to become the way through the wall, that is, 0 0 is set to 1 1 , so as to achieve the purpose of weight determination

Output path: an array simulation queue structure, pre recorded before a queue element index in the array, when it reaches the end, recursive backtracking back output path.

Note: BFS itself already contains the shortest property, so once they reach the end, it is the shortest route, the output can be.

#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;
}
Published 844 original articles · won praise 135 · Views 150,000 +

Guess you like

Origin blog.csdn.net/qq_42815188/article/details/105064238
Recommended