Leetcode 200: Number of Islands, leetcodeislands

Source: Internet
Author: User

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);    }}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.