diff --git a/0286-Walls-and-Gates/cpp-0286/main.cpp b/0286-Walls-and-Gates/cpp-0286/main.cpp index be0900d6..bf8a9a6a 100644 --- a/0286-Walls-and-Gates/cpp-0286/main.cpp +++ b/0286-Walls-and-Gates/cpp-0286/main.cpp @@ -1,6 +1,7 @@ /// Source : https://leetcode.com/problems/walls-and-gates/description/ /// Author : liuyubobobo /// Time : 2018-08-25 +/// Updated: 2019-06-12 #include #include @@ -15,30 +16,36 @@ using namespace std; class Solution { private: - int d[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; - int n, m; + const int d[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + int m, n; + + const int GATE = 0; + const int EMPTY = INT_MAX; + const int WALL = -1; public: void wallsAndGates(vector>& rooms) { - n = rooms.size(); - if(n == 0) + m = rooms.size(); + if(m == 0) return; - m = rooms[0].size(); - for(int i = 0; i < n; i ++) - for(int j = 0; j < m; j ++) - if(rooms[i][j] == 0) - bfs(rooms, i, j); + n = rooms[0].size(); + + bfs(rooms); return; } private: - void bfs(vector>& rooms, int startx, int starty){ + void bfs(vector>& rooms){ - vector> visited(n, vector(m, false)); queue, int>> q; - q.push(make_pair(make_pair(startx, starty), 0)); - visited[startx][starty] = true; + for(int i = 0; i < m; i ++) + for(int j = 0; j < n; j ++) + if(rooms[i][j] == GATE) + q.push(make_pair(make_pair(i, j), 0)); + + vector> visited(m, vector(n, false)); + while(!q.empty()){ int curx = q.front().first.first; int cury = q.front().first.second; @@ -49,19 +56,17 @@ class Solution { for(int i = 0; i < 4; i ++){ int newX = curx + d[i][0]; int newY = cury + d[i][1]; - if(inArea(newX, newY) && !visited[newX][newY] && rooms[newX][newY] >= 0){ + if(inArea(newX, newY) && !visited[newX][newY] && rooms[newX][newY] == EMPTY){ visited[newX][newY] = true; - if(rooms[newX][newY] > step + 1){ - rooms[newX][newY] = step + 1; - q.push(make_pair(make_pair(newX, newY), step + 1)); - } + rooms[newX][newY] = step + 1; + q.push(make_pair(make_pair(newX, newY), step + 1)); } } } } bool inArea(int x, int y){ - return x >= 0 && x < n && y >= 0 && y < m; + return x >= 0 && x < m && y >= 0 && y < n; } };