711094. Number Of Enclaves
Medium
Here is the generated Markdown blog post:
Number Of Enclaves
Slug: number-of-enclaves
Difficulty: Medium
Id: 711094
Topic Tags: DFS, Matrix, Graph, BFS, Data Structures, Algorithms
Company Tags: Google
Summary
The problem "Number Of Enclaves" involves a rectangular grid of cells where each cell is either land or water. The task is to find the number of enclaves in this grid, which are groups of connected land cells that do not share any borders with other land cells. This problem requires using graph traversal algorithms like Depth-First Search (DFS) or Breadth-First Search (BFS).
Detailed Explanation
To solve this problem, we can use a combination of DFS and BFS to count the number of enclaves.
Here's the step-by-step breakdown:
- Initialize a 2D array
gridto represent the rectangular grid. - Define a function
isLandCell(row, col)that checks if a given cell is land (1) or water (0). - Use DFS to traverse the grid from each land cell and mark all connected cells as visited.
- For each unvisited land cell, perform BFS to count the number of connected land cells that do not share any borders with other land cells. This will give us the total number of enclaves.
Time complexity: O(M*N), where M is the number of rows and N is the number of columns in the grid. Space complexity: O(M*N) for storing the visited cells during DFS and BFS traversal.
Optimized Solutions
Java
public int countEnclaves(int[][] grid) {
int enclaves = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1 && isLandCell(i, j)) {
enclaves += dfs(grid, i, j);
}
}
}
return enclaves;
}
private int dfs(int[][] grid, int row, int col) {
if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] == 0) {
return 0;
}
grid[row][col] = 0; // mark as visited
int count = 1;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0) continue;
int newRow = row + i;
int newCol = col + j;
if (newRow >= 0 && newRow < grid.length && newCol >= 0 && newCol < grid[0].length && grid[newRow][newCol] == 1) {
count += dfs(grid, newRow, newCol);
}
}
}
return count;
}
private boolean isLandCell(int row, int col) {
// check if the cell is land (1)
}