-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode1030.java
More file actions
50 lines (46 loc) · 1.9 KB
/
LeetCode1030.java
File metadata and controls
50 lines (46 loc) · 1.9 KB
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
import java.util.Arrays;
import java.util.Queue;
import java.util.LinkedList;
public class LeetCode1030 {
public static void main(String[] args) {
// 输入:rows = 1, cols = 2, rCenter = 0, cCenter = 0
// 输出:[[0,0],[0,1]]
System.out.println(
Arrays.deepToString(new Solution1030().allCellsDistOrder(1, 2, 0, 0)));
// 输入:rows = 2, cols = 2, rCenter = 0, cCenter = 1
// 输出:[[0,1],[0,0],[1,1],[1,0]]
System.out.println(
Arrays.deepToString(new Solution1030().allCellsDistOrder(2, 2, 0, 1)));
// 输入:rows = 2, cols = 3, rCenter = 1, cCenter = 2
// 输出:[[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]
System.out.println(
Arrays.deepToString(new Solution1030().allCellsDistOrder(2, 3, 1, 2)));
}
}
class Solution1030 {
public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
int[][] result = new int[rows * cols][2];
int[][] dirs = new int[][] { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
boolean[][] visited = new boolean[rows][cols];
Queue<int[]> queue = new LinkedList<int[]>();
queue.add(new int[] { rCenter, cCenter });
visited[rCenter][cCenter] = true;
int index = 0;
while (!queue.isEmpty()) {
int[] current = queue.poll();
// System.out.println("x: " + current[0] + " y: " + current[1]);
result[index][0] = current[0];
result[index][1] = current[1];
index++;
for (int[] dir : dirs) {
int x = current[0] + dir[0];
int y = current[1] + dir[1];
if (x >= 0 && x < rows && y >= 0 && y < cols && !visited[x][y]) {
queue.add(new int[] { x, y });
visited[x][y] = true;
}
}
}
return result;
}
}