Red Knight's Shortest Path

  • + 0 comments

    C++ BFS solution

    void printShortestPath(int n, int i_start, int j_start, int i_end, int j_end) {
        std::vector<std::tuple<int, int, std::string>> direct = {{-2, -1, "UL"}, {-2, 1, "UR"}, {0, 2, "R"},{2, 1, "LR"},{2, -1, "LL"},{0, -2, "L"}};
        // Print the distance along with the sequence of moves.
       queue<std::tuple<int, int, std::string>> pq;
        vector<vector<bool>> vis(n, vector<bool>(n, false));
        vis[i_start][j_start] = true;
        // add start point
        int steps = 0;
        pq.emplace(i_start, j_start, string(""));
        int step = 0;
        while(!pq.empty()) {
            int size = pq.size();
            steps++;
            while (size--) {
               auto [r, c, path] = pq.front();
                pq.pop();
                // reach target node
                if (r == i_end && c == j_end) {
                    cout << steps-1 << endl; 
                    cout << path << endl;
                    return;
                }
                for (const auto& [nb_r, nb_c, name]: direct) {
                    int new_r = r + nb_r;
                    int new_c = c + nb_c;
                    // validate node
                    if (new_r >= 0 && new_r <n && new_c>=0 && new_c <n && !vis[new_r][new_c]){
                        vis[new_r][new_c] = true;
                        pq.emplace(new_r, new_c, path + name + " ");
                        }
                    }
                }
            } 
        // not found any path
        cout << "Impossible" << endl;
    }