All reachable problem ---island
https://leetcode.com/problems/number-of-islands
Island problem, 可以是一张图上,1)flood fill, 2) number of islands, 3) max area of the island
Question
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Clarification & Assumption
Graph Representation
vertex: 所有是“1” 的点
edge: four directions 为 “1” 的点
High Level
Problem definition
this is an all-reachable nodes problem
starting from every 1 vertex, traversing all connected element
What traversal algorithm?
DFS1, DFS2, DFS3(for each vertex, traverse all possible reachable vertex, by depth order, and make sure each vertex visited once)
BFS(for each vertex, traverse all possible reachable vertex, by level/breath order, and make sure each vertex visited once)
Middle Level
Graph representation?
Method 1: 完全分开
graph representation
vertex, int[][]
edge: four direction {-1, 0} {1, 0}, {0, -1}, {0, 1}
visited: boolean visited[][]
Method 2: 把visited单独出来
graph representation
Vertex: cell (int x, int y)
edge: four direction {-1, 0} {1, 0}, {0, -1}, {0, 1}:
visited: enum / boolean visited[][]
Method 3: 全部合在一起
Graph Representation, vertex & edge together
Vertex& Edge
Graph
Node {int x, int y, int value, boolean visited, Set<Vertex> neighb}
TC & SC
TC: O(|V| + |E|) = O (5mn), SC: O(mn)
Method 1 DFS
Method 1 BFS (& DFS)
Method 3 BFS & DFS
Method 2 DFS & BFS for maximum area of island
Last updated