Matrix Cells in Distance Order LeetCode solution in Java

1
// --------------------Method 1----------------------
2

3
class Solution {
4
public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
5

6
int[][] res = new int[rows * cols][2];
7

8
int idx = 0;
9

10
for (int i = 0; i < rows; i++) {
11
for (int j = 0; j < cols; j++) {
12
res[idx][0] = i;
13
res[idx][1] = j;
14
idx++;
15
}
16
}
17

18
Arrays.sort(
19
res,
20
(a, b) -> {
21
int d1 = Math.abs(a[0] - rCenter) + Math.abs(a[1] - cCenter);
22
int d2 = Math.abs(b[0] - rCenter) + Math.abs(b[1] - cCenter);
23

24
return d1 - d2;
25
});
26

27
return res;
28
}
29
}
30

31
// --------------------Method 2--------------------
32

33
// class Solution {
34
// public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
35

36
// boolean [][]vis=new boolean[rows][cols];
37
// int [][]ans=new int[rows*cols][2];
38

39
// Queue<Pair> q=new LinkedList<>();
40
// q.add(new Pair(rCenter,cCenter));
41
// int idx=0;
42
// vis[rCenter][cCenter]=true;
43
// int [][]dir={{0,1},{1,0},{-1,0},{0,-1}};
44

45
// while(!q.isEmpty()){
46
// Pair curr=q.remove();
47
// ans[idx][0]=curr.r;
48
// ans[idx][1]=curr.c;
49
// idx++;
50

51
// for(int []d:dir){
52
// int nr=curr.r+d[0];
53
// int nc=curr.c+d[1];
54

55
// if(nr>=0 && nr<rows && nc>=0 && nc<cols && !vis[nr][nc]){
56
// vis[nr][nc]=true;
57
// q.add(new Pair(nr,nc));
58
// }
59
// }
60
// }
61

62
// return ans;
63
// }
64
// }
65

66
// class Pair{
67
// int r;
68
// int c;
69

70
// public Pair(int r, int c){
71
// this.r=r;
72
// this.c=c;
73
// }
74
// }

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0