|
| 1 | +package com.fishercoder.solutions.secondthousand; |
| 2 | + |
| 3 | +public class _1034 { |
| 4 | + public static class Solution1 { |
| 5 | + /** |
| 6 | + * My completely original solution. |
| 7 | + */ |
| 8 | + int[] dirs = new int[]{0, 1, 0, -1, 0}; |
| 9 | + |
| 10 | + public int[][] colorBorder(int[][] grid, int row, int col, int color) { |
| 11 | + int m = grid.length; |
| 12 | + int n = grid[0].length; |
| 13 | + boolean[][] visited = new boolean[m][n]; |
| 14 | + visited[row][col] = true; |
| 15 | + //copy the input as the final output so that we keep the input intact during dfs, otherwise, it'll lead to incorrect result like in test case 3 |
| 16 | + int[][] result = new int[m][n]; |
| 17 | + for (int i = 0; i < m; i++) { |
| 18 | + for (int j = 0; j < n; j++) { |
| 19 | + result[i][j] = grid[i][j]; |
| 20 | + } |
| 21 | + } |
| 22 | + return dfs(grid, row, col, color, m, n, grid[row][col], visited, result); |
| 23 | + } |
| 24 | + |
| 25 | + private int[][] dfs(int[][] grid, int row, int col, int color, int m, int n, int originalColor, boolean[][] visited, int[][] result) { |
| 26 | + if (row == 0 || col == 0 || row == m - 1 || col == n - 1 || neighborDiffColor(row, col, grid, originalColor, m, n)) { |
| 27 | + result[row][col] = color; |
| 28 | + } |
| 29 | + for (int i = 0; i < dirs.length - 1; i++) { |
| 30 | + int nextRow = dirs[i] + row; |
| 31 | + int nextCol = dirs[i + 1] + col; |
| 32 | + if (nextRow >= 0 && nextRow < m && nextCol >= 0 && nextCol < n && grid[nextRow][nextCol] == originalColor && !visited[nextRow][nextCol]) { |
| 33 | + visited[nextRow][nextCol] = true; |
| 34 | + dfs(grid, nextRow, nextCol, color, m, n, originalColor, visited, result); |
| 35 | + } |
| 36 | + } |
| 37 | + return result; |
| 38 | + } |
| 39 | + |
| 40 | + private boolean neighborDiffColor(int row, int col, int[][] grid, int originalColor, int m, int n) { |
| 41 | + //if any of the four neighbors has a different color, we consider this cell as a boarding cell as well as it's a boarder to this connected component |
| 42 | + for (int i = 0; i < dirs.length - 1; i++) { |
| 43 | + int nextRow = row + dirs[i]; |
| 44 | + int nextCol = col + dirs[i + 1]; |
| 45 | + if (nextRow >= 0 && nextCol >= 0 && nextRow < m && nextCol < n && grid[nextRow][nextCol] != originalColor) { |
| 46 | + return true; |
| 47 | + } |
| 48 | + } |
| 49 | + return false; |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments