Coloring A Border LeetCode solution in Java

1
class Solution {
2
public int[][] colorBorder(int[][] grid, int row, int col, int color) {
3
dfs(grid, row, col, grid[row][col]);
4
for (int i = 0; i < grid.length; i++) {
5
for (int j = 0; j < grid[0].length; j++) {
6
if (grid[i][j] < 0) {
7
grid[i][j] = color;
8
}
9
}
10
}
11

12
return grid;
13
}
14

15
int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
16

17
public void dfs(int[][] grid, int row, int col, int color) {
18
grid[row][col] = -color;
19
int count = 0;
20
for (int i = 0; i < 4; i++) {
21
int rowdash = row + dirs[i][0];
22
int coldash = col + dirs[i][1];
23

24
if (rowdash < 0
25
|| coldash < 0
26
|| rowdash >= grid.length
27
|| coldash >= grid[0].length
28
|| Math.abs(grid[rowdash][coldash]) != color) {
29
continue;
30
}
31
count++;
32

33
if (grid[rowdash][coldash] == color) {
34
dfs(grid, rowdash, coldash, color);
35
}
36
}
37
if (count == 4) {
38
grid[row][col] = color;
39
}
40
}
41
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0