广度优先搜索

广度优先搜索

from IPython.display import Image
Image(filename="./data/5_01.png",width=800,height=960)

output_1_0.png

一.寻找制高点

def bfs(set,m,n,matrix):
    dir=[[0,1],[0,-1],[1,0],[-1,0]]
    queue=list(set)
    
    while len(queue)>0:
        x,y=queue.pop()
        
        for d in dir:
            nx=x+d[0]
            ny=y+d[1]
            
            if 0<=nx and nx<m and 0<=ny and ny<n:
                if matrix[nx][ny]>=matrix[x][y]:
                    if (nx,ny) not in set:
                        queue.append((nx,ny))
                        set.add((nx,ny))
                        
                        
def solve(matrix):
    if not matrix:
        # 如果二维数组为空,那么就返回空
        return matrix
    
    m=len(matrix)
    n=len(matrix[0])
    
    # 上边的点的横坐标为0,纵坐标为0到n-1
    topPoint=set([(0,y) for y in range(n)])
    # 左边的点的横坐标为0到m-1,纵坐标为0
    leftPoint=set([(x,0) for x in range(m)])
    # 下边的点的横坐标为m-1,纵坐标为0到n-1
    bottomPoint=set([(m-1,y) for y in range(n)])
    # 右边的点的横坐标为0到m-1,纵坐标为0到n-1
    rightPoint=set([(x,n-1) for x in range(m)])
    
    # 依次调用4次dfs
    bfs(topPoint,m,n,matrix)
    bfs(leftPoint,m,n,matrix)
    bfs(bottomPoint,m,n,matrix)
    bfs(rightPoint,m,n,matrix)
    
    # 求集合的交集
    result=topPoint & leftPoint & bottomPoint & rightPoint
    
    return result

matrix=[
    [1,3,2,3,5],
    [3,4,5,6,3],
    [2,7,4,3,3],
    [5,2,2,3,1]
]

s=solve(matrix)
print(s)
{(1, 2), (1, 3), (2, 1)}

二.合法的括号

def isvalid(str):
    # 创建一个变量记录括号的数量
    count=0
    
    for c in str:
        # 遇到左括号就让变量加1
        if c=="(":
            count+=1
        elif c==")":
            count-=1

            if count<0:
                return False
            
    return count==0

def bfs(str):
    # 存放最终结果
    res=[]
    # 先把初始字符串加入队列
    queue=[str]
    
    # 队列不为空的时候就开始进行广度优先遍历
    while len(queue)>0:
        for i in range(len(queue)):
            if isvalid(queue[i]):
                res.append(queue[i])
        if len(res)>0:
            return list(set(res))
        
        temp=[]
        
        for s in queue:
            for i in range(len(s)):
                if s[i]=="(" or s[i]==")":
                    temp.append(s[:i]+s[i+1:])
                    
        queue=list(set(temp))
str="(((a))(a+(b)))"
bfs(str)
['(((a))(a+(b)))']
原文地址:https://www.cnblogs.com/LQ6H/p/12940559.html