首页 > 编程语言 >献芹奏曝-Python面试题-算法-DFS&BFS

献芹奏曝-Python面试题-算法-DFS&BFS

时间:2022-11-11 22:45:40浏览次数:59  
标签:count 面试题 Python self DFS range grid len def

上一篇:献芹奏曝-Python面试题 

      开篇的话:本文目的是收集和归纳力扣上的算法题,希望用python语言,竭我所能做到思路最清奇、代码最简洁、方法最广泛、性能最高效,了解常见题目,找到最利于记忆的答案,更加从容的应对面试。希望广思集益,共同进步。

深度优先搜索(DFS)与广度优先搜索(BFS)

 

一、岛屿篇

  1. 200. 岛屿数量(难度系数✯) 

    class Solution:
        def set_grid(self,grid,i,j):
            if i<0 or j<0 or i>=len(grid) or j>=len(grid[i]) or grid[i][j] == "0":
                return 
            grid[i][j] = "0"
            self.set_grid(grid,i,j-1) #左
            self.set_grid(grid,i,j+1) #右
            self.set_grid(grid,i-1,j) #上
            self.set_grid(grid,i+1,j) #下
    
        def numIslands(self, grid: List[List[str]]) -> int:
            # 边界条件
            if not grid:
                return 0
            # 统计岛屿个数
            count = 0
            # 双层for 遍历每个格子
            for i in range(len(grid)):
                for j in range(len(grid[i])):
                    if grid[i][j] == "1":
                        count += 1
                        self.set_grid(grid,i,j)
            return count
    DFS

    运行结果:1:耗时超过58%。2:内存超过59% 

    知识点/技巧:1:访问相邻结点(上、下、左、右)。2:判断base case(是否过界、是否为0)

    class Solution:
        def set_grid(self,grid,i,j):
            # 设置队列
            que = []
            que.append((i,j))
            while que:
                i,j=que.pop(0)
                grid[i][j] = "0"
                # 上 (i-1,j)
                if i>0 and grid[i-1][j] == "1":
                    grid[i-1][j] = "0"
                    que.append((i-1,j))
                # 下 (i+1,j)
                if i+1<len(grid) and grid[i+1][j] == "1":
                    grid[i+1][j] = "0"
                    que.append((i+1,j))
                # 左 (i,j-1)
                if j>0 and grid[i][j-1] == "1":
                    grid[i][j-1] = "0"
                    que.append((i,j-1))
                # 右 (i,j+1)
                if j+1<len(grid[i]) and grid[i][j+1] == "1":
                    grid[i][j+1] = "0"
                    que.append((i,j+1))
    
             
    
        def numIslands(self, grid: List[List[str]]) -> int:
            # 边界条件
            if not grid:
                return 0
            # 统计岛屿个数
            count = 0
            # 双层for 遍历每个格子
            for i in range(len(grid)):
                for j in range(len(grid[i])):
                    if grid[i][j] == "1":
                        count += 1
                        self.set_grid(grid,i,j)
            return count
    BFS

    运行结果:1:耗时超过97%。2:内存超过94% 

    知识点/技巧:1:通过队列实现广度优先搜索

  2. 463. 岛屿的周长(难度系数✯)

    class Solution:
        def islandPerimeter(self, grid: List[List[int]]) -> int:
            # 普通方法,看周边情况,
            count = 0
            for i in range(len(grid)):
                for j in range(len(grid[i])):
                    if grid[i][j] == 1:
                        count += self.get_count(grid,i,j)
            return count
        
        def get_count(self,grid,i,j):
            _count = 0 
            # 上
            if i-1<0 or grid[i-1][j]==0:
                _count += 1
            # 下
            if i+1==len(grid) or grid[i+1][j]==0:
                _count += 1
            # 左
            if j-1<0 or grid[i][j-1]==0:
                _count += 1
            # 右
            if j+1==len(grid[i]) or grid[i][j+1]==0:
                _count += 1   
            return _count
    直接法

    运行结果:1:耗时超过65%。2:内存超过78% 

    知识点/技巧:1:访问相邻结点(上、下、左、右)。2:如果相邻结点是0或者边 周长+1

    class Solution:
        count = 0
        def islandPerimeter(self, grid: List[List[int]]) -> int:
            # DFS方法,看周边情况,
            for i in range(len(grid)):
                for j in range(len(grid[i])):
                    if grid[i][j] == 1:
                        self.dfs(grid,i,j)
            return self.count
        
        def dfs(self,grid,i,j):
            if i<0 or j<0 or i>=len(grid) or j>=len(grid[i]) or grid[i][j] == 2 or grid[i][j] == 0:
                return 
            grid[i][j] = 2
            self.get_count(grid,i,j)
            self.dfs(grid,i,j-1) #左
            self.dfs(grid,i,j+1) #右
            self.dfs(grid,i-1,j) #上
            self.dfs(grid,i+1,j) #下
            
        def get_count(self,grid,i,j):
            # 上
            if i-1<0 or grid[i-1][j]==0:
                self.count += 1
            # 下
            if i+1==len(grid) or grid[i+1][j]==0:
                self.count += 1
            # 左
            if j-1<0 or grid[i][j-1]==0:
                self.count += 1
            # 右
            if j+1==len(grid[i]) or grid[i][j+1]==0:
                self.count += 1   
    DFS

    运行结果:1:耗时超过8%。2:内存超过14% 

    知识点/技巧:1:DFS

    class Solution:
        count = 0
        def islandPerimeter(self, grid: List[List[int]]) -> int:
            # DFS方法,看周边情况,
            for i in range(len(grid)):
                for j in range(len(grid[i])):
                    if grid[i][j] == 1:
                        self.dfs(grid,i,j)
            return self.count
        
        def dfs(self,grid,i,j):
            if i<0 or j<0 or i>=len(grid) or j>=len(grid[i]) or grid[i][j] == 2 or grid[i][j] == 0:
                return 
            grid[i][j] = 2
            result = self.get_count(grid,i,j)
            if "左" not in result:
                self.dfs(grid,i,j-1)
            if "右" not in result:
                self.dfs(grid,i,j+1) 
            if "上" not in result:
                self.dfs(grid,i-1,j) 
            if "下" not in result:
                self.dfs(grid,i+1,j)
            
        def get_count(self,grid,i,j):
            result = []
            if i-1<0 or grid[i-1][j]==0:
                self.count += 1
                result.append("上")
            if i+1==len(grid) or grid[i+1][j]==0:
                self.count += 1
                result.append("下")
            if j-1<0 or grid[i][j-1]==0:
                self.count += 1
                result.append("左")
            if j+1==len(grid[i]) or grid[i][j+1]==0:
                self.count += 1   
                result.append("右")
            return result
    DFS 优化版

    运行结果:1:耗时超过12%。2:内存超过15% 

    知识点/技巧:1:DFS 递归调用时进行优化。

    class Solution:
        count = 0
        def islandPerimeter(self, grid: List[List[int]]) -> int:
            # BFS方法,看周边情况,
            for i in range(len(grid)):
                for j in range(len(grid[i])):
                    if grid[i][j] == 1:
                        self.bfs(grid,i,j)
            return self.count
        
        def bfs(self,grid,i,j):
            # 设置队列
            que = []
            que.append((i,j))
            while que:
                i,j = que.pop(0)
                grid[i][j] = 2
                # 上
                if i-1<0 :
                    self.count += 1
                elif grid[i-1][j]==0:
                    self.count += 1
                elif grid[i-1][j]==1:
                    grid[i-1][j]==2
                    if (i-1,j) not in que:
                        que.append((i-1,j))
                
                # 下
                if i+1==len(grid) :
                    self.count += 1
                elif grid[i+1][j]==0:
                    self.count += 1
                elif grid[i+1][j]==1:
                    grid[i+1][j]==2
                    if (i+1,j) not in que:
                        que.append((i+1,j))
                    
                # 左
                if j-1<0 :
                    self.count += 1
                elif grid[i][j-1]==0:
                    self.count += 1
                elif grid[i][j-1]==1:
                    grid[i][j-1]==2
                    if (i,j-1) not in que:
                        que.append((i,j-1))
    
                # 右
                if j+1==len(grid[i]):
                    self.count += 1
                elif grid[i][j+1]==0:
                    self.count += 1
                elif grid[i][j+1]==1:
                    grid[i][j+1]==2
                    if (i,j+1) not in que:
                        que.append((i,j+1))
                    
    BFS

    运行结果:1:耗时超过8%。2:内存超过44% 

    知识点/技巧:1:BFS

  3. 695. 岛屿的最大面积 (难度系数✯✯)

  4. 827. 最大人工岛  (难度系数✯✯✯)

 

标签:count,面试题,Python,self,DFS,range,grid,len,def
From: https://www.cnblogs.com/YK2012/p/16672055.html

相关文章

  • Python语法糖之match-case
    目录概述基本语法和语义example1example2进阶用法如果在case写变量名只是为了不写if语句么?本博客主要参考为北京大学陈斌老师的下一站Python概述match-case是python3.1......
  • OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src
    原先一直以为数据集路径错误,调了半天也没用,后来打印图片列表,发现一个隐藏文件在终端运行 ls-a也出现了这个隐藏文件  删除 rm-rf.ipynb_checkpoints之后成功......
  • python中的运算符
    #1.算术运算符print('1.算术运算符')print('+1+2+3=',1+2+3)print('-10-5-1=',10-5-1)print('*2*2*3=',2*2*3)print('/7/2=',7/2)#除法,操......
  • Python获取IP地址
    Python获取IP地址一些情况下,我们需要通过Python获取电脑当前的IP地址,并执行一些操作(比如上传到数据库),则可以执行下面的命令:1.获取外网IP地址importrequestsprint(req......
  • 【面试】909- 59 道 CSS 面试题(附答案)
    CSS部分的面试题主要考察应试者对CSS基础概念模型的理解,例如文档流、盒模型、浮动、定位、选择器权重、样式继承等。很多应试者认为CSS很简单,没多少内容,面试就是面试JavaSc......
  • 数据降噪处理--python实现
    原文链接:https://blog.csdn.net/qq_38342510/article/details/121227880一、均值滤波1)算法思想 给定均值滤波窗口长度,对窗口内数据求均值,作为窗口中心点的数据的值,之后......
  • 回溯算法dfs: lc46全排列 lc47全排列ll
    result=[] defbacktrack(路径,选择列表):if满足结束条件:result.add(路径)returnfor选择in选择列表:做选择backtrack(路径,选择列表)撤销选择 46全......
  • python 修改ps背景颜色
    需要安装photoshop-python-api 1"""Changethecolorofthebackgroundandforeground."""2#Importlocalmodules3fromphotoshopimportSession4......
  • Python 监控web站点异常邮件提醒并自动重启
    生产环境中站点,如邮于访问量大出现异常不能正常运行,一般可以通过重启解决的。我们可以尝试通过Python监控监控web站点异常,发送邮件通知并自动重启服务。本文主要介绍Python......
  • #python笔记
    python笔记数据类型查看使用type()语句来查看数据的类型方法一:使用print直接输出信息print(type("黑马程序员")print(type("666"))print(type(11.345))方法二:......