Skip to content

Commit 7d8efee

Browse files
authored
Create 1034. Coloring A Border.java
1 parent 88b2e34 commit 7d8efee

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// dfs
2+
3+
class Solution {
4+
5+
boolean[][] isVisited;
6+
int[] dr = {-1, 1, 0, 0};
7+
int[] dc = {0, 0, -1, 1};
8+
9+
public int[][] colorBorder(int[][] grid, int row, int col, int color) {
10+
isVisited = new boolean[grid.length][grid[0].length];
11+
12+
List<int[]> borders = new ArrayList<>();
13+
dfs (grid, row, col, grid[row][col], borders);
14+
15+
for (int[] b : borders) {
16+
grid[b[0]][b[1]] = color;
17+
}
18+
19+
return grid;
20+
}
21+
22+
void dfs(int[][] grid, int row, int col, int gridColor, List<int[]> borders) {
23+
isVisited[row][col] = true;
24+
25+
boolean isBorder = false;
26+
for (int i = 0; i<4; i++) {
27+
int nr = row + dr[i];
28+
int nc = col + dc[i];
29+
30+
if (nr<0 || nr>=grid.length || nc<0 || nc>=grid[0].length) { // 테두리
31+
isBorder = true;
32+
continue;
33+
}
34+
35+
if (grid[nr][nc] != gridColor) {
36+
isBorder = true;
37+
continue;
38+
}
39+
40+
if (!isVisited[nr][nc]) {
41+
dfs(grid, nr, nc, gridColor, borders);
42+
}
43+
}
44+
if (isBorder) borders.add(new int[]{row, col});
45+
}
46+
}

0 commit comments

Comments
 (0)