[leetcode] 200. Number of islands

Given a two-dimensional grid consisting of'1'(land) and'0' (water), the number of islands is calculated. An island is surrounded by water and connected by adjacent land in either horizontal or vertical directions. You can assume that all four sides of the grid are surrounded by water.

Example 1:

Input:
11110
11010
11000
00000

Output: 1

thinking

Linear scanning of the entire two-dimensional grid, if a node contains 1, then it is used as the root node to start breadth-first search. Put it in the queue and set the value to 0 to mark access to the node. Iteratively search each node in the queue until the queue is empty.

Even

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid or not grid[0]:
            return 0
        res = 0
        queue = []
        m, n = len(grid), len(grid[0])
        marked = [[False for _ in range(n)] for _ in range(m)]
        print(m,n)
        for i in range(m):
            for j in range(n):
                # As long as it is land and has not been visited, it is possible to use BFS to discover and mark the land connected to it.
                if not marked[i][j] and grid[i][j]=='1':
                    res+=1
                    queue.append((i,j))
                    marked[i][j] = True
                    while queue:
                        a,b = queue.pop(0)
                        dx = [-1,0,1,0]
                        dy = [0,1,0,-1]
                        for z in range(4):
                            x = a+dx[z]
                            y = b+dy[z]
                            # If I do not cross the border, have not been visited, and still have land, I will continue to put in the queue, put in the queue at the same time, remember that the tag has been visited.
                            if m>x>=0 and n>y>=0 and not marked[x][y] and grid[x][y]=='1':
                                queue.append((x,y))
                                marked[x][y] = True
        return res

Reference resources

from typing import List
from collections import deque


class Solution:
    #        x-1,y
    # x,y-1    x,y      x,y+1
    #        x+1,y
    # Directional array, which represents the offset of the horizontal and vertical coordinates relative to the four directions of the current position, is a common technique.
    directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]

    def numIslands(self, grid: List[List[str]]) -> int:
        m = len(grid)
        # Special judgement
        if m == 0:
            return 0
        n = len(grid[0])
        marked = [[False for _ in range(n)] for _ in range(m)]
        count = 0
        # Starting from the first line and the first grid, try a DFS operation on each grid
        for i in range(m):
            for j in range(n):
                # As long as it is land and has not been visited, it is possible to use BFS to discover and mark the land connected to it.
                if not marked[i][j] and grid[i][j] == '1':
                    # Counts can be understood as connected components. You can count them after the breadth-first traversal is completed.
                    # It's also possible to put this line of code in [position 1].
                    count += 1
                    queue = deque()
                    queue.append((i, j))
                    # Note: Mark here that you have visited
                    marked[i][j] = True
                    while queue:
                        cur_x, cur_y = queue.popleft()
                        # Get coordinates in four directions
                        for direction in self.directions:
                            new_i = cur_x + direction[0]
                            new_j = cur_y + direction[1]
                            # If I do not cross the border, have not been visited, and still have land, I will continue to put in the queue, put in the queue at the same time, remember that the tag has been visited.
                            if 0 <= new_i < m and 0 <= new_j < n and not marked[new_i][new_j] and grid[new_i][new_j] == '1':
                                queue.append((new_i, new_j))
                                #[Pay special attention] Once you're in the queue, mark it as accessed immediately, and the semantics are clear: if you're in the queue, sooner or later, you'll traverse it.
                                # Instead of marking up when you're out of the queue
                                #[Special attention] Remarking when you are out of the queue will cause many duplicate nodes to enter the queue, resulting in duplicate operations. If you do not write the correct place, the code will be seriously timed out.
                                marked[new_i][new_j] = True
                    #[Location 1]
        return count


if __name__ == '__main__':
    grid = [['1', '1', '1', '1', '0'],
            ['1', '1', '0', '1', '0'],
            ['1', '1', '0', '0', '0'],
            ['0', '0', '0', '0', '0']]

The method of infection, refer to ___________.

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid or not grid[0]:
            return 0
        res = 0
        m, n = len(grid), len(grid[0])
        d = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        for i in range(m):
            for j in range(n):
                if grid[i][j] == '1':
                    grid[i][j] = '#'
                    res += 1
                    queue = [(i, j)]
                    while queue:
                        a, b = queue.pop(0)
                        for dx, dy in d:
                            x = a + dx
                            y = b + dy
                            if 0 <= x < m and 0 <= y < n and grid[x][y] == '1':
                                grid[x][y] = '#'
                                queue.append((x, y))
        return res
            

 

Posted by jib0 on Wed, 02 Oct 2019 04:56:27 -0700