leetcode 200 : Number of Islands

作者: 今晚开什么码  发布:2019-11-15

leetcode 200 : Number of Islands

Leetcode 200 Number of Islands,leetcodeislands

Given a 2d grid map of '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

对于任何找到的陆地,寻找四周能够到达的陆地(同一片陆地)并改变其值(这里改0)以防再次被统计到。需要注意题目输入的是字符串数组。

这里在递归方法开始前就设定条件防止越界。

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
  ans
end

def 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)
  end
end

 

200 Number of Islands,leetcodeislands Given a 2d grid map of '1' s (land) and '0' s (water), count the number of islands. An island is surrounded by water and is formed...

Number of Islands

Total Accepted: 8305 Total Submissions: 38192

Given a 2d grid map of '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

[思路]

这道题有点像 word search的简化版. 每遇到'1'后, 开始向四个方向 递归搜索. 搜到后变为'0', 因为相邻的属于一个island. 然后开始继续找下一个'1'.

[CODE]

 

public class Solution {
    public int numIslands(char[][] grid) {
        int count = 0;
        for(int i=0; i=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);
    }
}

 

200 : Number of Islands Number of Islands Total Accepted: 8305 Total Submissions: 38192 Given a 2d grid map of 1 s (land) and 0 s (water), count the number of islands. An...

本文由今晚开什么码发布于今晚开什么码,转载请注明出处:leetcode 200 : Number of Islands

关键词:

上一篇:宠物收养场
下一篇:没有了