Пожалуйста, подпишитесь на официальный канал Codeforces в Telegram по ссылке https://t.me/codeforces_official. ×

Finding Paths in a Labyrinth: A C++ Solution

Правка en1, от ego_for_success, 2024-10-17 13:30:48

Solving the Labyrinth: Finding a Path from Start to End

Hi everyone!

Today, I'm excited to share a solution for a classic problem in competitive programming: finding a path in a labyrinth from a start point 'A' to an end point 'B'. This problem is not just about navigating through walls; it's also about efficiently determining the shortest path and outputting the sequence of moves. Let’s dive into the problem!


Problem Statement

You are given a labyrinth represented as a grid of characters, where: - . indicates a floor (walkable space). - # indicates a wall (non-walkable space). - A is the starting point. - B is the endpoint.

Your task is to find out whether there is a path from A to B, and if so, to determine the shortest path and its description (using characters for directions: L, R, U, D).

Input Format

  1. Two integers n and m (height and width of the map).
  2. n lines of m characters describing the labyrinth.

Output Format

  • Print "YES" if there is a path; otherwise, print "NO".
  • If a path exists, print the length of the shortest path and the sequence of moves.

Constraints

  • ( 1 \leq n, m \leq 1000 )

Example Input

5 8
########
#.A#...#
#.##.#B#
#......#
########

Example Output

YES
9
LDDRRRRRU

Solution Approach

The solution involves using Breadth-First Search (BFS), which is suitable for finding the shortest path in an unweighted grid like this labyrinth. Below is a breakdown of the solution:

  1. Initialization:
  • Read the labyrinth dimensions and grid.
  • Identify the starting point A and the endpoint B.
  • Initialize a queue for BFS, a visited matrix, and a parent tracking matrix to reconstruct the path later.
  1. BFS Algorithm:
  • Begin from the starting point A.
  • For each cell, explore its neighbors (up, down, left, right).
  • If a neighbor is walkable (. or B) and not visited, mark it as visited, record its parent, and add it to the queue.
  • Stop when you reach B.
  1. Path Reconstruction:
  • If B is reached, backtrack from B to A using the parent matrix to determine the sequence of moves.
  • Reverse the sequence for the correct order and output the result.

C++ Implementation

Here’s the complete code that implements the above logic:

#include <bits/stdc++.h>
#define ll long long
#define endl "\n"
using namespace std;

int n, m;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    cin >> n >> m;
    vector<vector<char>> v(n, vector<char>(m));
    vector<vector<int>> vis(n, vector<int>(m, 0));
    vector<vector<pair<int, int>>> par(n, vector<pair<int, int>>(m, {-1, -1}));

    pair<int, int> st, ed;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> v[i][j];
            if (v[i][j] == 'A') {
                st = {i, j};
            }
            if (v[i][j] == 'B') {
                ed = {i, j};
            }
        }
    }

    queue<pair<int, int>> q;
    q.push(st);
    vis[st.first][st.second] = 1;

    while (!q.empty()) {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();

        if (x == ed.first && y == ed.second) break;

        for (auto [dx, dy, dir] : vector<tuple<int, int, char>>{{1, 0, 'D'}, {-1, 0, 'U'}, {0, 1, 'R'}, {0, -1, 'L'}}) {
            int nx = x + dx, ny = y + dy;
            if (nx >= 0 && ny >= 0 && nx < n && ny < m && (v[nx][ny] == 'B' || v[nx][ny] == '.') && !vis[nx][ny]) {
                q.push({nx, ny});
                par[nx][ny] = {x, y};
                vis[nx][ny] = 1;
            }
        }
    }

    if (!vis[ed.first][ed.second]) {
        cout << "NO" << endl;
    } else {
        cout << "YES" << endl;
        vector<char> ans;
        int x = ed.first, y = ed.second;

        while (x != st.first || y != st.second) {
            auto [a, b] = par[x][y];
            if (x > a) ans.push_back('D');
            else if (x < a) ans.push_back('U');
            else if (y > b) ans.push_back('R');
            else if (y < b) ans.push_back('L');
            x = a; y = b;
        }
        reverse(ans.begin(), ans.end());
        cout << ans.size() << endl;
        for (auto it : ans) cout << it;
        cout << endl;
    }

    return 0;
}

Conclusion

This implementation efficiently finds the shortest path in a labyrinth using BFS and reconstructs the path through backtracking. Feel free to try this out with different labyrinth configurations! If you have any questions or suggestions, please leave a comment.

Thanks for reading, and happy coding!

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en3 Английский ego_for_success 2024-10-17 13:33:09 7692
en2 Английский ego_for_success 2024-10-17 13:31:53 6952
en1 Английский ego_for_success 2024-10-17 13:30:48 4872 Initial revision (published)