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
| class Solution { int m, n, color; int[][] grid, ans; int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public int[][] colorBorder(int[][] grid, int row, int col, int color) { this.grid = grid; this.color = color; m = grid.length; n = grid[0].length; ans = new int[m][n]; dfs(row, col); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (ans[i][j] == 0) ans[i][j] = grid[i][j]; } } return ans; }
private void dfs(int x, int y) { int cnt = 0; for (int[] dir : dirs) { int nx = x + dir[0], ny = y + dir[1]; if (nx < 0 || nx >= m || ny < 0 || ny >= n) continue; if (grid[x][y] != grid[nx][ny]) continue; else ++cnt; if (ans[nx][ny] != 0) continue; ans[nx][ny] = -1; dfs(nx, ny); } ans[x][y] = cnt == 4 ? grid[x][y] : color; } }
|