Created
June 9, 2018 01:20
-
-
Save bilbo3000/4eec3f255deaedeb2aa50af5bee6f24b 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
import java.util.Arrays; | |
import java.util.LinkedList; | |
import java.util.Queue; | |
class Solution { | |
class Coor { | |
int x, y, d; | |
Coor(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 } }; | |
public int[][] postOffices(int row, int col, int[][] offices) { | |
int[][] result = new int[row][col]; | |
for (int[] r : result) { | |
Arrays.fill(r, -1); | |
} | |
Queue<Coor> queue = new LinkedList<>(); | |
for (int[] coor : offices) { | |
result[coor[0]][coor[1]] = 0; | |
Coor c = new Coor(coor[0], coor[1], 0); | |
queue.add(c); | |
} | |
while (!queue.isEmpty()) { | |
Coor front = queue.remove(); | |
for (int[] dir : dirs) { | |
int x = front.x + dir[0]; | |
int y = front.y + dir[1]; | |
if (x < 0 || x >= row || y < 0 || y >= col || result[x][y] != -1) | |
continue; | |
result[x][y] = front.d + 1; | |
queue.add(new Coor(x, y, front.d + 1)); | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment