Created
June 12, 2018 01:32
-
-
Save bilbo3000/f9005e0f90c2a9b08a2f21e511cfd5ca to your computer and use it in GitHub Desktop.
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
public class Solution { | |
class Node{ | |
int x, y; | |
int d; | |
Node(int x, int y, int d) { | |
this.x = x; | |
this.y = y; | |
this.d = d; | |
} | |
} | |
private int[][] dirs = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; | |
private int INF = 2147483647; | |
/** | |
* @param rooms: m x n 2D grid | |
* @return: nothing | |
*/ | |
public void wallsAndGates(int[][] rooms) { | |
int m = rooms.length; | |
int n = rooms[0].length; | |
Queue<Node> q = new LinkedList<>(); | |
for (int i = 0; i < m; i++) { | |
for (int j = 0; j < n; j++) { | |
if (rooms[i][j] == 0) { | |
q.add(new Node(i, j, 0)); | |
} | |
} | |
} | |
while (!q.isEmpty()) { | |
Node front = q.remove(); | |
for (int[] dir : dirs) { | |
int x = front.x + dir[0]; | |
int y = front.y + dir[1]; | |
if (x < 0 || x >= m || y < 0 || y >= n || rooms[x][y] != INF) continue; | |
rooms[x][y] = front.d + 1; | |
Node node = new Node(x, y, front.d + 1); | |
q.add(node); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment