286. Walls and Gates

class Solution {
public:
    void wallsAndGates(vector<vector<int>>& rooms) {
        int dir[] = {0, -1, 0, 1, 0};
        const int INF = 2147483647;
        queue<pair<int, int>> accessible;
        int m = rooms.size(), n = m ? rooms[0].size() : 0;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (!rooms[i][j]) accessible.push(make_pair(i, j));

        while(!accessible.empty()) {
            int x = accessible.front().first;
            int y = accessible.front().second;
            accessible.pop();
            for (int i = 0; i < 4; i++) {
                int xx = x + dir[i], yy = y + dir[i + 1];
                if (xx >= 0 && xx < m && yy >= 0 && yy < n)
                    if (rooms[xx][yy] == INF) {
                        rooms[x + dir[i]][y + dir[i + 1]] = rooms[x][y] + 1;
                        accessible.push(make_pair(x + dir[i], y + dir[i + 1]));
                    }
            }
        }
        return;
    }
};

results matching ""

    No results matching ""