0

The following code is the shortest path algorithm code I am using: Algorithm to find the shortest path in a grid

bool isValid(std::vector<std::vector<int>>& grid, int i, int j) {
    if(i < 0 || i >= grid.size() || j < 0 || j >= grid[i].size() || grid[i][j] != 0)
        return false;
    return true;
}

int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
    if(grid.empty())
        return 0;

    if(grid[0][0] == 1 || grid[grid.size()-1][grid.size()-1] == 1) 
        return -1;

    int m = grid.size(), n = grid[0].size();
    pair<int, int> start = {0,0};
    pair<int, int> end = {m-1, n-1};
    vector<vector<bool>> visited(m, vector<bool>(n, false));
    // no priority queue needed: the graph is not weighted
    vector<std::pair<int,int>> q;
    q.push_back(start);
    visited[start.first][start.second] = true;
    int count = 1;

    while(!q.empty())
    {
        // just iterate the vector and populate a new one
        vector<std::pair<int,int>> q2;
        for(auto const& cur: q) {
            if(cur.first == end.first && cur.second == end.second)
                return count;
            for(auto dir : dirs)
            {
                int x = cur.first, y = cur.second;

                if(isValid(grid, x + dir[0], y + dir[1]))
                    x += dir[0], y += dir[1];

                if(!visited[x][y])
                {
                    visited[x][y] = true;
                    q2.push_back({x,y});
                }
            }
        }
        count++;
        q = q2; // prepare for next iteration
    }
    return -1;
}

This algorithm works in terms of that it counts the total number of nodes that the shortest path would go through, however, I would like to print the coordinate of every node it passes through.

Using example 2 from the question page (https://leetcode.com/problems/shortest-path-in-binary-matrix/), the input grid is

[0,0,0]

[1,1,0]

[1,1,0]

The output would be 4 for this question, but I would like to have [0][0]->[1][0]->[2][1]->[2][2] as the result. Any ideas on how to trace the shortest path taken with this code? Thanks a ton!

2
  • Using the Chebyshev distance I see. I was expecting Manhatten distance. Commented Oct 23, 2021 at 22:27
  • 2
    I would say dynamic programming with path reconstruction Commented Oct 23, 2021 at 23:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.