[template question] breadth first search (BFS)

Posted by designerguy on Fri, 08 Oct 2021 03:41:11 +0200

1, Maze problem

[Title Description]
Given an n × A two-dimensional integer array of m is used to represent a maze. The array contains only 0 or 1, where 0 represents the road that can be taken and 1 represents the wall that cannot be passed.
Initially, a person is located at the upper left corner (1,1), and it is known that the person can move one position in any direction of up, down, left and right at a time.
How many times does the person need to move from the upper left corner to the lower right corner (n,m).
The data guarantees that the numbers at (1,1) and (n,m) are 0, and there must be at least one path.

[input format]
The first line contains two integers n and m.
The next n lines, each containing m integers (0 or 1), represent the complete two-dimensional array maze.

[output format]
Outputs an integer representing the minimum number of moves from the upper left corner to the lower right corner.

[data range]
1≤n,m≤100

[input example]

5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

[output example]

8
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;

typedef pair<int, int> PII;
const int N = 110;
int g[N][N], dis[N][N];
int dx[4] = { 0, 1, 0, -1 }, dy[4] = { 1, 0, -1, 0 };
int n, m;

int bfs()
{
    dis[1][1] = 0;
    queue<PII> Q;
    Q.push({ 1, 1 });
    while (Q.size())
    {
        auto t = Q.front();
        Q.pop();
        for (int i = 0; i < 4; i++)
        {
            int x = t.first + dx[i], y = t.second + dy[i];
            if (x >= 1 && x <= n && y >= 1 && y <= m && g[x][y] == 0 && dis[x][y] == -1)
            {
                dis[x][y] = dis[t.first][t.second] + 1;
                Q.push({ x, y });
            }
        }
    }
    return dis[n][m];
}

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            cin >> g[i][j];
    memset(dis, -1, sizeof dis);
    cout << bfs() << endl;
    return 0;
}

2, Eight digital issues

[Title Description]
In a 3 × In the grid of 3, the 8 numbers 1 ∼ 8 and an x are exactly distributed in the 3 × 3 in the grid.
For example:

1 2 3
x 4 6
7 5 8

During the game, x can be exchanged with one of its up, down, left and right directions (if any).
Our purpose is to change the grid into the following arrangement (called correct arrangement) through exchange:

1 2 3
4 5 6
7 8 x

For example, the graphics in the example can be correctly arranged by successfully exchanging x with numbers in the right, bottom and right directions.
The exchange process is as follows:

1 2 3   1 2 3   1 2 3   1 2 3
x 4 6   4 x 6   4 5 6   4 5 6
7 5 8   7 5 8   7 x 8   7 8 x

Now, I'll give you an initial grid. Please find out how many times you need to exchange to get the correct arrangement.

[input format]
The input occupies one line and will be 3 × The initial grid of 3 is drawn.
For example, if the initial mesh is as follows:

1 2 3 
x 4 6 
7 5 8 

Then the input is 1 2 3 x 4 6 7 5 8

[output format]
The output occupies one line and contains an integer, indicating the minimum number of exchanges.
If there is no solution, output − 1.

[input example]

2  3  4  1  5  x  7  6  8

[output example]

19
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;

string start, ans = "12345678x";
unordered_map<string, int> dis;
int dx[4] = { 0, 1, 0, -1 }, dy[4] = { 1, 0, -1, 0 };

int bfs()
{
    dis[start] = 0;
    queue<string> Q;
    Q.push(start);
    while (Q.size())
    {
        string t = Q.front();
        Q.pop();
        if (t == ans) return dis[t];
        int idx = t.find('x');//The subscript corresponding to the character 'x' was found
        //Mapping one-dimensional length to two-dimensional coordinates
        int x = idx / 3, y = idx % 3;
        for (int i = 0; i < 4; i++)
        {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx >= 0 && nx < 3 && ny >= 0 && ny < 3)
            {
                //Swap corresponding characters in one-dimensional string
                int d = dis[t];
                swap(t[nx * 3 + ny], t[idx]);
                if (!dis.count(t))
                {
                    dis[t] = d + 1;
                    Q.push(t);
                }
                swap(t[nx * 3 + ny], t[idx]);//Note: restore t
            }
        }
    }
    return -1;
}

int main()
{
    char c;
    for (int i = 0; i < 9; i++)
    {
        cin >> c;
        start += c;
    }
    cout << bfs() << endl;
    return 0;
}

Topics: C C++ Algorithm Graph Theory bfs