⬅ Previous Topic
Word Ladder II - All Shortest Transformation SequencesNext Topic ⮕
Check if a Graph is Bipartite using DFS⬅ Previous Topic
Word Ladder II - All Shortest Transformation SequencesNext Topic ⮕
Check if a Graph is Bipartite using DFSTopic Contents
Given a 2D grid of size N x M
consisting of '1's (land) and '0's (water), your task is to find the number of distinct islands. An island is a group of connected '1's (land) in 4 directions (horizontal and vertical). Two islands are considered distinct if and only if their shape (relative position of land cells) is different.
shapes
to store unique island signatures.shapes
set.shapes
.function numDistinctIslands(grid) {
const rows = grid.length, cols = grid[0].length;
const visited = Array.from({ length: rows }, () => Array(cols).fill(false));
const shapes = new Set();
const directions = [
[0, 1, 'R'], // right
[0, -1, 'L'], // left
[1, 0, 'D'], // down
[-1, 0, 'U'] // up
];
function dfs(r, c, path, dir) {
if (r < 0 || c < 0 || r >= rows || c >= cols || visited[r][c] || grid[r][c] === 0) return;
visited[r][c] = true;
path.push(dir);
for (const [dr, dc, d] of directions) {
dfs(r + dr, c + dc, path, d);
}
path.push('B'); // Backtrack
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] === 1 && !visited[r][c]) {
const path = [];
dfs(r, c, path, 'S'); // Start
shapes.add(path.join(''));
}
}
}
return shapes.size;
}
// Example Usage
console.log("Distinct Islands:", numDistinctIslands([
[1,1,0,0],
[1,0,0,0],
[0,0,1,1],
[0,0,0,1]
])); // Output: 2
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(m * n) | Even in the best case, we must visit every cell to check if it's land or water and track unique shapes. |
Average Case | O(m * n) | Each cell is visited once, and DFS explores each connected component, tracking the shape. |
Worst Case | O(m * n) | In the worst case (e.g., entire grid is land), DFS explores all cells, and all must be encoded and compared. |
O(m * n)
Explanation: In the worst case, all cells are part of different islands, requiring separate shape strings and a visited matrix of the same size.
⬅ Previous Topic
Word Ladder II - All Shortest Transformation SequencesNext Topic ⮕
Check if a Graph is Bipartite using DFSYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.