Leetcode 200 Number of Islands, leetcodeislands

Source: Internet
Author: User

Leetcode 200 Number of Islands, leetcodeislands

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:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

For any land found, find the land around which it can reach (the same land) and change its value (change it to 0 here) to prevent it from being recorded again. Note that the question is entered as a string array.

Here, conditions are set before the recursive method starts to prevent cross-border operations.

def num_islands(grid)  return 0 if not grid  ans = 0  grid.length.times do |i|    grid[0].length.times do |j|      if grid[i][j] == '1'        ans += 1        extend(grid,i,j)      end    end  end  ansenddef extend(grid,i,j)  if i<grid.length and j <grid[0].length and i>=0 and j>=0 and grid[i][j] == '1'    grid[i][j] = '0'    extend(grid,i+1,j)    extend(grid,i,j+1)    extend(grid,i-1,j)    extend(grid,i,j-1)  endend

 

Related Article

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.