Skip to content

Instantly share code, notes, and snippets.

@bilbo3000
Created June 9, 2018 01:20
Show Gist options
  • Save bilbo3000/4eec3f255deaedeb2aa50af5bee6f24b to your computer and use it in GitHub Desktop.
Save bilbo3000/4eec3f255deaedeb2aa50af5bee6f24b to your computer and use it in GitHub Desktop.
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