Skip to content

Commit

Permalink
Add 286_Walls_and_Gates.java
Browse files Browse the repository at this point in the history
  • Loading branch information
seanprashad committed Apr 15, 2022
1 parent 34c7296 commit 988f870
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions Tree Breadth First Search/286_Walls_and_Gates.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
class Solution {
public void wallsAndGates(int[][] rooms) {
Set<int[]> gates = new HashSet<>();

for (int row = 0; row < rooms.length; row++) {
for (int col = 0; col < rooms[row].length; col++) {
if (rooms[row][col] == 0) {
gates.add(new int[] { row, col });
}
}
}

Queue<int[]> q = new LinkedList<>();

for (int[] gate : gates) {
q.offer(gate);
}

int distance = 0;
boolean[][] visited = new boolean[rooms.length][rooms[0].length];

while (!q.isEmpty()) {
int size = q.size();

for (int i = 0; i < size; i++) {
int[] coord = q.poll();
int x = coord[0], y = coord[1];

if (x < 0 || y < 0 || x >= rooms.length || y >= rooms[0].length ||
rooms[x][y] == -1 || visited[x][y]) {
continue;
}

rooms[x][y] = Math.min(rooms[x][y], distance);
visited[x][y] = true;

q.offer(new int[] { x + 1, y });
q.offer(new int[] { x - 1, y });
q.offer(new int[] { x, y + 1 });
q.offer(new int[] { x, y - 1 });
}

++distance;
}
}
}

0 comments on commit 988f870

Please sign in to comment.