Skip to content

Instantly share code, notes, and snippets.

@rayjcwu
Created April 14, 2014 17:57
Show Gist options
  • Save rayjcwu/10669603 to your computer and use it in GitHub Desktop.
Save rayjcwu/10669603 to your computer and use it in GitHub Desktop.
Given a 2d array as a maze with '. (open space)' and 'G (guard)', update each open spaces with the distance to its nearest guard.
Example ->
matrix :
. . . G .
. . G . .
. . . . G
answer ->
2 1 1 G 1
2 1 G 1 1
2 1 1 1 G
public char[][] distMaze(char[][] maze) {
final int M = maze.length;
if (M == 0) return maze;
final int N = maze[0].length;
if (N == 0) return maze;
Queue <Point> q = new LinkedList<Point>();
for (int y = 0; y < M; y++) {
for (int x = 0; x < N; x++) {
if (maze[y][x] == 'G') {
q.add(new Point(y, x, 0));
}
}
}
if (q.size() == 0) {
for (int y = 0; y < M; y++) {
for (int x = 0; x < N; x++) {
maze[y][x] = '-';
}
}
} else {
while(!q.isEmpty()) {
Point p = q.remove();
relax2(maze, y - 1, x - 1, p, q);
relax2(maze, y - 1, x , p, q);
relax2(maze, y - 1, x + 1, p, q);
relax2(maze, y , x - 1, p, q);
relax2(maze, y , x + 1, p, q);
relax2(maze, y + 1, x - 1, p, q);
relax2(maze, y + 1, x , p, q);
relax2(maze, y + 1, x + 1, p, q);
}
}
return maze;
}
public void relax2(char[][] maze, int y, int x, Point p, Queue<Point> q) {
if (relax(maze, y, x, p)) {
q.add(new Point(y, x, maze[y][x] - '0');
}
}
// return true if update maze[y][x]
public boolean relax(char[][] maze, int y, int x, Point p) {
final int M = maze.length;
final int N = maze[0].length;
if (y < 0 || y >= M || x < 0 || x >= N || maze[y][x] != '.') {
return false;
}
maze[y][x] = '0' + p.dist + 1;
return true;
}
class Point {
int y;
int x;
int dist;
public Point(int y, int x, int dist) {
this.y = y;
this.x = x;
this.dist = dist;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment