leetcode463 岛屿的周长

通过dfs,判断交界处进行加1

class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        visit=[[0]*len(grid[0]) for _ in range(len(grid))]

        def dfs(x,y,count,visit):

            if grid[x][y]==0:
                count+=1
                return count
            else:
                visit[x][y]=1
                for item in [(0,1),(1,0),(-1,0),(0,-1)]:
                    if x+item[0]>=len(grid) or x+item[0]<0:
                        count+=1
                    if y+item[1]>=len(grid[0]) or y+item[1]<0:
                        count+=1
                    if 0<=x+item[0]<len(grid) and 0<=y+item[1]<len(grid[0]) and visit[x+item[0]][y+item[1]]!=1 :

                        count=dfs(x+item[0],y+item[1],count,visit)


            return count

        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j]==1:
                    result=dfs(i,j,0,visit)
                    return result

迭代方法

class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:

        count=0       
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j]==1:
                    for item in [(0,1),(1,0),(-1,0),(0,-1)]:
                        if i+item[0]>=len(grid) or i+item[0]<0:
                            count+=1
                        if j+item[1]>=len(grid[0]) or j+item[1]<0:
                            count+=1
                        if 0<=i+item[0]<len(grid) and 0<=j+item[1]<len(grid[0]) and grid[i+item[0]][j+item[1]]==0:

                            count+=1
        return count
全部评论

相关推荐

shtdbb_:还不错,没有让你做了笔试再挂你
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务