leetcode 1034 Coloring A Border 解法 python

一.问题描述

Given a 2-dimensional grid of integers, each value in the grid represents the color of the grid square at that location.

Two squares belong to the same connected component if and only if they have the same color and are next to each other in any of the 4 directions.

The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column).

Given a square at location (r0, c0) in the grid and a color, color the border of the connected component of that square with the given color, and return the final grid.

Example 1:

Input: grid = [[1,1],[1,2]], r0 = 0, c0 = 0, color = 3
Output: [[3, 3], [3, 2]]

Example 2:

Input: grid = [[1,2,2],[2,3,2]], r0 = 0, c0 = 1, color = 3
Output: [[1, 3, 3], [2, 3, 3]]

Example 3:

Input: grid = [[1,1,1],[1,1,1],[1,1,1]], r0 = 1, c0 = 1, color = 2
Output: [[2, 2, 2], [2, 1, 2], [2, 2, 2]]

二.解题思路

感觉类似一个深度搜索,我是用递归实现的

核心思想就是探索当前点的上下左右四个点,如果要探索的点与当前点数字相同,并且没有被探索过,就递归到这个探索点

要用一个数组来记录所有当前探索过的点,因为上下左右同时递归,可能会和之前探索过的点重合,即原来连通区域是一个环的话。因此这步要小心一点。

同时要注意,只染色边界,如果点在边界就直接染色,如果这个点4周都已经染过了,那就不用染了。

我直接新开一个数组来保存final grid, 因为grid一遍迭代一遍更改,不好判断该点与周围点的关系,因为更改不是同步进行的,到时候判断该不该染色就不好判断。

这就引出来了我本次的最大bug。。。一直通过不了,因为是final grid的初始我是直接list.cop()这个函数。但是由于grid是个二维的,因此里面的每个维度其实还是指向同个内存,导致grid到后面也在变。解决方法是用copy包的deepcopy函数。

不是很难,主要就是注意细节

今天弄太久没找一些高效实现,如果发现了后面更新

更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我

欢迎大家一起套路一起刷题一起ac

三.源码

import copy
class Solution:
    def colorBorder(self, grid: List[List[int]], r0: int, c0: int, color: int) -> List[List[int]]:
        #flag is used to record the point we have entered
        flag=[[False]*len(grid[0]) for i in range(0,len(grid))]
        # pay attention to this step, do not use list.copy()
        grid_copy=copy.deepcopy(grid)  
        self.helper(grid,grid_copy,r0,c0,color,flag)
        return grid_copy
    
    def helper(self,grid,grid_copy,r1,c1,color,flag):
        row=len(grid)
        col=len(grid[0])
        samesum=0  # used to judge whether this point is the order
        flag[r1][c1]=True
        x=1
        y=1
        for i in range(0,2):
            x=-x
            if r1+x<0 or r1+x>=row:
                    continue
            if grid[r1+x][c1]==grid[r1][c1]:
                samesum+=1
                if not flag[r1+x][c1]:
                     self.helper(grid,grid_copy,r1+x,c1,color,flag)
        for i in range(0,2):
            y=-y
            if c1+y<0 or c1+y>=col:
                    continue
            if grid[r1][c1+y]==grid[r1][c1]:
                samesum+=1
                if not flag[r1][c1+y]:
                    self.helper(grid,grid_copy,r1,c1+y,color,flag)
                    
        if r1==0 or r1==row-1 or c1==0 or c1==col-1 or samesum!=4:
            grid_copy[r1][c1]=color
            
                
        

 

你可能感兴趣的:(leetcode算法从零到结束,leetcode,python,算法)