算法-二维矩阵各点到0值的距离

算法之二维矩阵各点到0值的距离

  • 给定一个矩阵,返回各个节点到0点位置的最短路径

如:
{0,1,1,1}
{1,1,1,0}
{1,0,1,1}

返回:
[0, 1, 2, 1]
[1, 1, 1, 0]
[1, 0, 1, 1]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package tmp;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/**
* Created by cdx0312
*/
public class Test {
public static void main(String[] args) {
int[][] arr = new int[3][4];
arr[0] = new int[]{0,1,1,1};
arr[1] = new int[]{1,1,1,0};
arr[2] = new int[]{1,0,1,1};
int[][] res = getResult(arr);
for (int i = 0; i < 3; i++)
System.out.println(Arrays.toString(res[i]));
}
private static int[][] getResult(int[][] arr) {
int M = arr.length;
int N = arr[0].length;
Queue<Point> queue = new LinkedList<>();
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (arr[i][j] == 0)
queue.offer(new Point(i, j));
else
arr[i][j] = Integer.MAX_VALUE;
}
}
while (!queue.isEmpty()) {
Point point = queue.poll();
int x = point.x, y = point.y;
int target = arr[x][y];
if (x >= 1 && arr[x-1][y] > target + 1) {
arr[x - 1][y] = arr[x][y] + 1;
queue.offer(new Point(x-1, y));
}
if (x < M - 1 && arr[x+1][y] > target + 1) {
arr[x + 1][y] = arr[x][y] + 1;
queue.offer(new Point(x+1, y));
}
if (y >= 1 && arr[x][y-1] > target + 1) {
arr[x][y - 1] = arr[x][y] + 1;
queue.offer(new Point(x, y-1));
}
if (y < N - 1 && arr[x][y+1] > target + 1) {
arr[x][y + 1] = arr[x][y] + 1;
queue.offer(new Point(x, y+1));
}
}
return arr;
}
static class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}
Donate comment here