程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> leetcode 200 : Number of Islands

leetcode 200 : Number of Islands

編輯:C++入門知識

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


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved