-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
34c7296
commit 988f870
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} |