Leetcode 200: Number of Islands, leetcodeislands
Number of IslandsTotal Accepted:8305Total Submissions:38192
Given a 2d grid map'1'
S (land) and'0'
S (water), count 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.
Example 1:
11110110101100000000
Answer: 1
Example 2:
11000110000010000011
Answer: 3
[Idea]
This question is a bit like a simplified version of word search. after each occurrence of '1', recursive search is performed in four directions. after searching, it becomes '0' because the adjacent one belongs to an island. then start searching for the next '1 '.
[CODE]
public class Solution { public int numIslands(char[][] grid) { int count = 0; for(int i=0; i<grid.length; i++) { for(int j=0; j<grid[0].length; j++) { if(grid[i][j]=='1') { search(grid, i, j); ++count; } } } return count; } private void search(char[][] grid, int x, int y) { if(x<0 || x>=grid.length || y<0 || y>=grid[0].length || grid[x][y]!='1') return; grid[x][y] = '0'; search(grid, x-1, y); search(grid, x+1, y); search(grid, x, y-1); search(grid, x, y+1); }}