(int[][] grid)
| 15 | static boolean hasArticulationPoint; //tells if graph has an articulation point |
| 16 | static int time; //global time counter used by DFS |
| 17 | public int minDays(int[][] grid) { |
| 18 | rows = grid.length; |
| 19 | cols = grid[0].length; |
| 20 | hasArticulationPoint = false; |
| 21 | time = 0; |
| 22 | int landCells = 0, islandCount = 0; |
| 23 | |
| 24 | int[][] discoveryTime = new int[rows][cols]; // Time when a cell is first discovered |
| 25 | // Lowest discovery time reachable from the subtree rooted at this cell |
| 26 | int[][] lowestReachable = new int[rows][cols]; |
| 27 | // Parent of each cell in DFS tree |
| 28 | int[][] parentCell = new int[rows][cols]; |
| 29 | |
| 30 | // Initialize arrays with default values (note -1 means there is no parent) |
| 31 | for (int i = 0; i < rows; i++) { |
| 32 | Arrays.fill(discoveryTime[i], -1); |
| 33 | Arrays.fill(lowestReachable[i], -1); |
| 34 | Arrays.fill(parentCell[i], -1); |
| 35 | } |
| 36 | |
| 37 | // Traverse the grid to find islands and articulation points |
| 38 | for (int i = 0; i < rows; i++) { |
| 39 | for (int j = 0; j < cols; j++) { |
| 40 | if (grid[i][j] == 1) { //1 means a node in graph. |
| 41 | landCells++; |
| 42 | if (discoveryTime[i][j] == -1) { // If not yet visited |
| 43 | // Start DFS for a new island |
| 44 | findArticulationPoints(grid,i,j,discoveryTime,lowestReachable,parentCell); |
| 45 | islandCount++; //no of dfs calls means number of connected components |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | // Determine the minimum number of days to disconnect the grid |
| 52 | if (islandCount == 0 || islandCount >= 2) return 0; // Already disconnected or no land |
| 53 | if (landCells == 1) return 1; // Only one land cell |
| 54 | if (hasArticulationPoint) return 1; // An articulation point exists |
| 55 | return 2; // Need to remove any two land cells |
| 56 | } |
| 57 | |
| 58 | private void findArticulationPoints(int[][] grid,int row,int col,int[][] discoveryTime,int[][] lowestReachable,int[][] parentCell) { |
| 59 | discoveryTime[row][col] = time; //first node discovery is 0, note that time is global |
nothing calls this directly
no test coverage detected