leetcode 200. Number of Islands

200. Number of Islands
題目描述

1 代表島嶼, 0 代表海洋, 1 被 0 包圍算作一個島嶼. 只要1被連接, 都只能算一個島嶼.

解題思路

用DFS解題. 遍歷grid所有點, 如果grid[i][j]==1, 則對grid[i][j]由四個方向進行DFS, 把所有經過的點標記爲x(表示去過), 所以每次遇到grid[i][j]==1的點一定是一個新的島嶼.

代碼
Python

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid:
            return 0
        
        def explore(i,j):
            # i was here
            grid[i][j] = 'x' 
            if i > 0 and grid[i - 1][j] == '1':
                explore(i - 1,j)               
            if j > 0 and grid[i][j - 1] == '1':
                explore(i,j - 1)            
            if i < col - 1 and grid[i + 1][j] == '1':
                explore(i + 1,j)     
            if j < row - 1 and grid[i][j + 1] == '1':
                explore(i,j + 1)
        
        noOfIsland = 0      
        col = len(grid)
        row = len(grid[0])
 
        for i in range(col):
            for j in range(row):
                if grid[i][j] == '1':          
                    noOfIsland += 1      
                    # Mark all the points in this island i.e all the points that can be reached from this point
                    explore(i,j)
                
        return noOfIsland
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章