leetcode 200. Number of Islands

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:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

具體的思路可以見我的博客園的博客:https://www.cnblogs.com/Weixu-Liu/p/10712642.html

在這個題中,我用python重新寫B(tài)FS,在寫B(tài)FS中,可以新建立一個列表,把位置下標(biāo)用元組表示,加到列表中就行。

python代碼:
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        sum = 0
        q = []
        m = len(grid)
        if m == 0:
            return 0
        n = len(grid[0])
        dx = [0,0,1,-1]
        dy = [1,-1,0,0]
        for r in range(m):
            for c in range(n):
                if grid[r][c] == '1':
                    grid[r][c] == '0'
                    q.append((r,c))
                    while len(q):
                        Q = q.pop(0)
                        index_r = Q[0]
                        index_c = Q[1]
                        for i in range(4):
                            x = index_r + dx[i]
                            y = index_c + dy[i]
                            if x >= 0 and x < m and y >= 0 and y < n and grid[x][y] == '1':
                                grid[x][y] = '0'
                                q.append((x,y))
                    sum += 1
        return sum

PS

不能寫grid[r, c] == '0',這個是在NumPy中的array數(shù)組上能用的。。。在列表就行不通了,o(╯□╰)o

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容