490. The Maze

class Solution {
public:
    bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
        n = maze.size();
        m = n ? maze[0].size() : 0;
        roll(maze, start);
        return visited.count(destination);
    }
private:
    set<vector<int>> visited;
    int n, m;
    vector<int> dir = {0, -1, 0, 1, 0};
    void roll(vector<vector<int>>& maze, vector<int> st) {
        if (visited.count(st)) return;
        visited.insert(st);
        for (int i = 0; i < 4; i++) {
            int I = st[0], J = st[1];
            while (I + dir[i] >= 0 && I + dir[i] < n  && 
                   J + dir[i + 1] >= 0 && J + dir[i + 1] < m && 
                   !maze[I + dir[i]][J + dir[i + 1]])
                I += dir[i], J += dir[i + 1];
            roll(maze, {I, J});
        }
        return;
    }
};

results matching ""

    No results matching ""