Day53-图论

110. 字符串接龙

110. 字符串迁移

无权图,没必要用dj等算法,仅仅使用深搜或者广搜;当然,广搜最合适,因为第一次出现目标点,就是最短路径的长度!

难点如何构造图?------仅仅一个字符不相同即可!

python 复制代码
def edge(s,t):
    count = 0
    for i in range(len(s)):
        if s[i] != t[i]:
            count +=1
    return count == 1

def main():
    n = int(input())
    beginStr,endStr = input().split()
    graph = []
    if beginStr == endStr:
        print(0)
        return
    for i in range(n):
        graph.append(input())
    queue = [[beginStr,1]]
    visited = [0] * n
    while queue:
        cur,hight = queue.pop(0)
        if edge(cur,endStr):
            print(1+hight)
            return
        for i in range(n):
            if edge(cur,graph[i]) and not visited[i]:
                queue.append([graph[i],hight+1])
                visited[i] = 1
    print(0)


if __name__ == '__main__':
    main()

105. 有向图的完全可达性

105. 有向图的完全联通

这个题用深搜和广搜都可以,但是根据题意很容易想到,用邻接表存储图肯定是最方便的。

python 复制代码
def dfs(graph,x,visited):
    if visited[x]:
        return
    visited[x] = 1
    for y in graph[x]:
        dfs(graph,y,visited)

def main():
    n,m = map(int,input().split())
    graph = [[] for _ in range(n+1)]
    for _ in range(m):
        s,t = map(int,input().split())
        graph[s].append(t)
    visited = [0] * (n+1)
    dfs(graph,1,visited)
    print(1 if sum(visited)==n else -1)

if __name__ == '__main__':
    main()

106. 岛屿的周长

106. 海岸线计算

不要被图论迷惑,不需要任何搜索技巧,仅仅是遍历,只要是岛屿边界【水或者是陆地】,+1即可

python 复制代码
DIR = [[1,0],[0,1],[-1,0],[0,-1]]

def main():
    n,m = map(int,input().split())
    graph = [[0] * (m + 2) for _ in range(n + 2)]
    for i in range(n):
        row = list(map(int,input().split()))
        for j in range(m):
            graph[i+1][j+1] = row[j]
    res = 0
    for i in range(1,n+1):
        for j in range(1,m+1):
            if graph[i][j] == 1:
                for d in DIR:
                    nexti = i+d[0]
                    nextj = j+d[1]
                    if not graph[nexti][nextj]:
                        res +=1
    print(res)
                
if __name__ == '__main__':
    main()
相关推荐
老鼠只爱大米2 小时前
LeetCode经典算法面试题 #84:柱状图中最大的矩形(单调栈、分治法等四种方法详细解析)
算法·leetcode·动态规划·单调栈·分治法·柱状图最大矩形
C雨后彩虹2 小时前
羊、狼、农夫过河
java·数据结构·算法·华为·面试
Elastic 中国社区官方博客2 小时前
使用瑞士风格哈希表实现更快的 ES|QL 统计
大数据·数据结构·sql·elasticsearch·搜索引擎·全文检索·散列表
lpfasd1232 小时前
PyGithub用法详解
git·python·github
给我来一根3 小时前
用户认证与授权:使用JWT保护你的API
jvm·数据库·python
重生之后端学习3 小时前
19. 删除链表的倒数第 N 个结点
java·数据结构·算法·leetcode·职场和发展
aini_lovee3 小时前
严格耦合波(RCWA)方法计算麦克斯韦方程数值解的MATLAB实现
数据结构·算法·matlab
安特尼3 小时前
推荐算法手撕集合(持续更新)
人工智能·算法·机器学习·推荐算法
白云千载尽3 小时前
LQR与MPC.入门知识与实验
python·控制·mpc·lqr