Skip to content

Commit

Permalink
286 codes updated.
Browse files Browse the repository at this point in the history
  • Loading branch information
liuyubobobo committed Jun 13, 2019
1 parent 05fe52a commit ff08d81
Showing 1 changed file with 24 additions and 19 deletions.
43 changes: 24 additions & 19 deletions 0286-Walls-and-Gates/cpp-0286/main.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/// Source : https://leetcode.com/problems/walls-and-gates/description/
/// Author : liuyubobobo
/// Time : 2018-08-25
/// Updated: 2019-06-12

#include <iostream>
#include <vector>
Expand All @@ -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<vector<int>>& 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<vector<int>>& rooms, int startx, int starty){
void bfs(vector<vector<int>>& rooms){

vector<vector<bool>> visited(n, vector<bool>(m, false));
queue<pair<pair<int, int>, 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<vector<bool>> visited(m, vector<bool>(n, false));

while(!q.empty()){
int curx = q.front().first.first;
int cury = q.front().first.second;
Expand All @@ -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;
}
};

Expand Down

0 comments on commit ff08d81

Please sign in to comment.