leetcode刷题总结 python版

leetcode 200. Number of Islands

2019-07-09  本文已影响0人  PJCK

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重新写BFS,在写BFS中,可以新建立一个列表,把位置下标用元组表示,加到列表中就行。

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数组上能用的。。。在列表就行不通了,o(╯□╰)o

上一篇下一篇

猜你喜欢

热点阅读