Problems like "given an 2D binary grid grid which represents a map of land and water, return the number of islands, an island is XXXX".
200. Number of Islandsopen
1020. Number of Enclavesopen
1254. Number of Closed Islands
1905. Count Sub Islandsopen
695. Max Area of Island
Ref: labuladong 题解
Number of Islands
200. Number of Islands
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.
privatevoiddfs_and_mark(int row, int col, char[][] grid) { intM= grid.length, N = grid[0].length;
if(isLand(grid[row][col])) { flood(row,col,grid);//Turn this land into water. //Then apply this method to surrounding grid. Notice the limit of grid's boundary if(row>=1) dfs_and_mark(row-1,col,grid); if(row <= M-2) dfs_and_mark(row+1,col,grid); if(col>=1) dfs_and_mark(row,col-1,grid); if(col <= N-2) dfs_and_mark(row,col+1,grid); } }