学python的第十二天---小蓝(3)

一、迷宫(DFS)

在这里插入图片描述

print("DDDDRRURRRRRRDRRRRDDDLDDRDDDDDDDDDDDDRDDRRRURRUURRDDDDRDRRRRRRDRRURRDDDRRRRUURUUUUUUULULLUUUURRRRUULLLUUUULLUUULUURRURRURURRRDDRRRRRDDRRDDLLLDDRRDDRDDLDDDLLDDLLLDLDDDLDDRRRRRRRRRDDDDDDRR")
n, m = 30, 50
a = [[0 for i in range(m)] for j in range(n)]
vis = [[100000 for i in range(m)] for j in range(n)]
t = [[0 for i in range(m)] for j in range(n)]
for i in range(n):
    res = input()
    for j in range(m):
        a[i][j] = res[j]

dx = [0, -1, 1, 0]
dy = [1, 0, 0, -1]
c = ["R", "U", "D", "L"]
pos = 0
res = [" " for i in range(100000)]
ans = 100000000
ss = ""

def pd(x, y):
    if x < 0 or x >= n or y < 0 or y >= m or a[x][y] == '1' or t[x][y] != 0:
        return False
    else:
        return True


def DFS(x, y, pos):
    global ans, ss
    if pos > ans:
        return
    if x == 29 and y == 49:
        s = "".join(res[:pos])
        if ans > pos:
            ans = pos
            ss = s
        elif pos == ans and s < ss:
            ss = s
        return
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if pd(nx, ny) and pos + 1 <= vis[nx][ny]:
            t[nx][ny] = 1
            vis[nx][ny] = pos + 1
            res[pos] = c[i]
            DFS(nx, ny, pos + 1)
            t[nx][ny] = 0


t[0][0] = 1
vis[0][0] = 0
DFS(0, 0, 0)
print(ss)

二、跳蚱蜢(BFS)

在这里插入图片描述
这道题就先转换一下,一开始是蚱蜢跳,然后转换成空盘子跳
然后要判重

def insertq(q,dir,news,vis):
    pos=news[1]#0的位置
    status=news[0]
    insertpos=(pos+dir+9)%9#找到0应该放的位置
    #将字符串转为列表
    t=list(status)
    t[pos],t[insertpos]=t[insertpos],t[pos]
    addStatus="".join(t)
    if addStatus not in vis:
        vis.add(addStatus)
        q.append((addStatus,insertpos,news[2]+1))


q=[("012345678",0,0)]#模拟队列
vis=set()#用来判重
vis.add("012345678")
while q:
    news=q.pop(0)
    if news[0]=="087654321":#说明到了目标状态,输出最少步数
        print(news[2])
        break
    insertq(q,-2,news,vis)
    insertq(q, -1, news, vis)
    insertq(q, 1, news, vis)
    insertq(q, 2, news, vis)

Set使用方式

# set 的定义 变量名=set()
intSet = set()
stringSet = set()

s1 = "测试1"
s2 = "测试2"
s3 = "测试3"

# 2. 插入操作
stringSet.add(s3)
stringSet.add(s2)

# 5.返回集合元素数量
print("前2次插入操作完成后的元素数量为%d\n" % len(stringSet))  # 注意这里要使用 % 进行格式化输出
stringSet.add(s1)
print("前3次插入操作完成后的元素数量为%d\n" % len(stringSet))

# 6.遍历整个集合
for ele in stringSet:
    print(ele, end=' ')
print()

# 3. 删除操作
stringSet.discard(s3)

print("删除操作完成后的元素数量为%d\n" % len(stringSet))
for ele in stringSet:
    print(ele, end=' ')
print()

# 4. 判断是否存在此元素
if s2 in stringSet:
    print("存在元素")
else:
    print("不存在元素")

python的字典

相当于C++的map
在 Python 中我们不叫映射,也不叫 map,我们称作字典。用法跟 Java 和 c++ 都是有一定区别的。

  1. 字典的创建。
massege={
    
    '小':'123124543643','xiaohua':'17855666','LiMing':'1249699859456'}

#或者创建空的字典
empty_dict = {
    
    }
#或者使用元组作为key
group_dict = {
    
    (60, 99):'good', 100:'nice'}
  1. 字典的添加。
# 如果字典内不含有相应的Key值,则会执行添加操作
dict[key]=value
  1. 字典的修改。
# 如果字典内含有相应的Key值,则会执行更新操作
dict[key]=new_value

# 使用update()修改
# update() 方法可使用一个字典所包含的 key-value 对来更新己有的字典。如果有就修改,没有就添加。
dict.update({
    
    'key':123,'key2':234})
  1. 字典的删除。
del dict['key']  # 删除键是'key'的条目
dict.clear()      # 清空字典所有条目
del dict          # 删除字典
  1. 字典的访问。
dict = {
    
    'Name': 'Zara', 'Age': '7'} 
print (dict['Name'])

#当然如果key值不存在,将会抛出异常
#也可以是用get()方法,不存在会返回None,但不会抛出异常
print(dict.get('Name')) 

三、七段码(DFS+并查集)

在这里插入图片描述

n,ans=10,0
use=[0 for i in range(n)]
e=[[0 for i in range(n)]for j in range(n)]
fa=[0 for i in range(n)]

def init():
    # 连边建图,e[i][j] == 1  表示第i段和第j段灯管相邻
    # a b c d e f g
    # 1 2 3 4 5 6 7
    e[1][2]=e[1][6]=1
    e[2][1]=e[2][7]=e[2][3]=1
    e[3][2]=e[3][4]=e[3][7]=1
    e[4][3]=e[4][5]=1
    e[5][4]=e[5][6]=e[5][7]=1
    e[6][1]=e[6][5]=e[6][7]=1
    e[7][2]=e[7][3]=e[7][5]=e[7][6]=1

def find(u):
    if fa[u]==u:
        return u
    fa[u]=find(fa[u])
    return fa[u]

def dfs(d):
    global ans
    if d>7:
        for i in range(1,7+1):
            fa[i]=i#初始化
        for i in range(1,7+1):
            for j in range(1,7+1):
                if e[i][j] and use[i] and use[j]:
                    fx=find(i)
                    fy=find(j)
                    if fx!=fy:
                        fa[fx]=fy
        k=0
        for i in range(1,7+1):
            if use[i] and fa[i]==i:
                k+=1
        if k==1:
            ans+=1#说明所有亮灯属于一个集合
        return
    use[d]=1#打开这个灯
    dfs(d+1)
    use[d]=0#关闭这个灯
    dfs(d+1)

init()
dfs(1)
print(ans)

并查集

在这里插入图片描述
在这里插入图片描述
初始化

maxn=200
fa=[]
def init():
    for i in range(maxn+1):
        fa.append(i)

查询


def find(x):
    if fa[x]==x:
        return x
    else:
        return find(fa[x])

带路径压缩的查询,可以节省很多时间

def find(x):
    if fa[x]==x:
        return x
    else:
        fa[x]=find(fa[x])
        return fa[x]

合并

def merge(x,y):
    fa[find(x)]=find(y)

四、合根植物(并查集)

在这里插入图片描述

n,m=map(int,input().split())
k=int(input())
t=1
fa=[]

def init():
    for i in range(m*n+5):
        fa.append(i)
def find(x):
    if fa[x]==x:
        return x
    else:
        fa[x]=find(fa[x])
        return fa[x]

def merge(x,y):
    fa[find(x)]=find(y)

init()

for i in range(k):
    x,y=map(int,input().split())
    merge(x,y)
ans=0

for i in range(m*n):
    index=i+1
    if(fa[index]==index):
        ans+=1
print(ans)

五、跳石头(整数二分)

在这里插入图片描述

最短的最长----二分

l,n,m=map(int,input().split())
a=[]
for i in range(n):
    t=int(input())
    a.append(t)
a.append(l)
left,right=0,l

def check(u):
    res=0
    pos=0
    for i in range(0,n+1):
        if a[i]-pos<u:
            res+=1
        else:
            pos=a[i]
    if res<=m:
        return True
    return False


while left<right:
    mid=(left+right+1)//2
    # print(mid)
    if check(mid):
        left=mid
    else:
        right=mid-1
print(left)

猜你喜欢

转载自blog.csdn.net/qq_51408826/article/details/129897548