题目:

There are N network nodes, labelled 1 to N.

Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.

Now, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1.

Note:
N will be in the range [1, 100].
K will be in the range [1, N].
The length of times will be in the range [1, 6000].
All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 1 <= w <= 100.

解题思路:

本题很像是树的遍历,找出离根节点最远的叶子节点。但是与树不一样的是,节点之间存在回路。如图我是构造的一组测试数据。我的想法是从根节点开始,首先找出与根节点有直通的第一层节点并将这一层所有节点入栈,同时用一个数组保存根节点与每个节点的最短延时。

1. 首先为节点定义结构体

class Node(object):
def __init__(self, inx):
self.inx = inx #节点序号
self.childList = [] #所有与之直连的节点列表
self.childDis = [] #到达直接节点的最小延时,下标与childList下标一致

2.遍历times,建立节点之间的直连关系

nodeList = [None for x in range(N+1)]
for i in times:
if nodeList[i[0]] == None:
node = Node(i[0]);
node.childList.append(i[1])
node.childDis.append(i[2])
nodeList[i[0]] = node
#print node.inx,node.childList,node.childDis
#print nodeList[i[0]].inx,nodeList[i[0]].childList,nodeList[i[0]].childDis
else:
nodeList[i[0]].childList.append(i[1])
nodeList[i[0]].childDis.append(i[2])

3.从K节点开始寻找最大延时节点,将过程中遍历到的节点入栈(类似广度遍历的思想),找出K能到达的所有节点,并用数组dp记录最短延时。

dp = [6001 for x in range(N+1)]
dp[0] = dp[K]= 0
stack = []
stack.append(K)
visit = set()
visit.add(K)
while len(stack) > 0:
tmp = stack.pop(0)
if nodeList[tmp] == None:
continue
for i in range(len(nodeList[tmp].childList)):
if dp[nodeList[tmp].childList[i]] > nodeList[tmp].childDis[i] + dp[tmp]: #注,这里是关键一步,判断是否有更小延时路径
dp[nodeList[tmp].childList[i]] = nodeList[tmp].childDis[i] + dp[tmp]
if nodeList[tmp].childList[i] not in visit:
visit.add(nodeList[tmp].childList[i])

完整代码如下:

class Node(object):
def __init__(self, inx):
self.inx = inx
self.childList = []
self.childDis = []
class Solution(object):
def networkDelayTime3(self, times, N, K):
#build level relation
nodeList = [None for x in range(N+1)]
for i in times:
if nodeList[i[0]] == None:
node = Node(i[0]);
node.childList.append(i[1])
node.childDis.append(i[2])
nodeList[i[0]] = node
#print node.inx,node.childList,node.childDis
#print nodeList[i[0]].inx,nodeList[i[0]].childList,nodeList[i[0]].childDis
else:
nodeList[i[0]].childList.append(i[1])
nodeList[i[0]].childDis.append(i[2]) dp = [6001 for x in range(N+1)]
dp[0] = dp[K]= 0
stack = []
stack.append(K)
visit = set()
visit.add(K)
while len(stack) > 0:
tmp = stack.pop(0)
if nodeList[tmp] == None:
continue
for i in range(len(nodeList[tmp].childList)):
if dp[nodeList[tmp].childList[i]] > nodeList[tmp].childDis[i] + dp[tmp]:
dp[nodeList[tmp].childList[i]] = nodeList[tmp].childDis[i] + dp[tmp]
if nodeList[tmp].childList[i] not in visit:
visit.add(nodeList[tmp].childList[i])
stack.append(nodeList[tmp].childList[i]) #print dp
if 6001 in dp:
return -1
else:
res = dp[1]
for i in range(1,len(dp)):
if res < dp[i]:
res = dp[i]
return res

【leetcode】Network Delay Time的更多相关文章

  1. 【LeetCode】堆 heap(共31题)

    链接:https://leetcode.com/tag/heap/ [23] Merge k Sorted Lists [215] Kth Largest Element in an Array (无 ...

  2. 【LeetCode】BFS(共43题)

    [101]Symmetric Tree 判断一棵树是不是对称. 题解:直接递归判断了,感觉和bfs没有什么强联系,当然如果你一定要用queue改写的话,勉强也能算bfs. // 这个题目的重点是 比较 ...

  3. 【LeetCode】深搜DFS(共85题)

    [98]Validate Binary Search Tree [99]Recover Binary Search Tree [100]Same Tree [101]Symmetric Tree [1 ...

  4. 【LeetCode】图论 graph(共20题)

    [133]Clone Graph (2019年3月9日,复习) 给定一个图,返回它的深拷贝. 题解:dfs 或者 bfs 都可以 /* // Definition for a Node. class ...

  5. 【LeetCode】743. Network Delay Time 解题报告(Python)

    [LeetCode]743. Network Delay Time 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: ht ...

  6. 【LeetCode】代码模板,刷题必会

    目录 二分查找 排序的写法 BFS的写法 DFS的写法 回溯法 树 递归 迭代 前序遍历 中序遍历 后序遍历 构建完全二叉树 并查集 前缀树 图遍历 Dijkstra算法 Floyd-Warshall ...

  7. 【LeetCode】449. Serialize and Deserialize BST 解题报告(Python)

    [LeetCode]449. Serialize and Deserialize BST 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/pro ...

  8. 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)

    [LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...

  9. 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

    [LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...

随机推荐

  1. Unity 声音与录音与麦克风实时播放

    Unity AudioSource与MicroPhone以及AudioClip之间的关系. 下面是一个声音,长度为7秒钟,声音的实际数据本质是由采样点组成的的列表,一秒钟内的采样点数就是采样频率,下面 ...

  2. ubuntu16.04+Titan Xp安装显卡驱动+Cuda9.0+cudnn

    硬件环境 ubuntu 16.04LTS + windows10 双系统 NVIDIA TiTan XP 显卡(12G) 软件环境 搜狗输入法 显卡驱动:LINUX X64 (AMD64/EM64T) ...

  3. TCP中三次挥手四次握手

    1.TCP连接 手机能够使用联网功能是因为手机底层实现了TCP/IP协议,可以使手机终端通过无线网络建立TCP连接.TCP协议可以对上层网络提供接口,使上层网络数据的传输建立在“无差别”的网络之上. ...

  4. Spring Boot(十七):使用 Spring Boot 上传文件

      上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个 Spring Boot 上传文件的小案例. 1.pom 包配置 我们使用 Spring Boot 版本 ...

  5. jenkins pipline和jenkinsfile

    Jenkins Pipeline(或简称为 "Pipeline")是一套插件,将持续交付的实现和实施集成到 Jenkins 中. Jenkins Pipeline 提供了一套可扩展 ...

  6. html中的锚点设置

    html中的锚点 一.页面内跳转的锚点设置 页面内的跳转需要两步: 方法一: ①:设置一个锚点链接去找喵星人:(注意:href属性的属性值最前面要加#) ②:在页面中需要的位置设置锚点<a na ...

  7. Flask-wtf导入Regexp规则库验证手机号码合法性(测试通过)

    手机号码在项目有着很重要的地位,保证用户输入的号码准确无误就显得很关键. 废话不多说,现在页面中引入Regexp规则库: from wtforms.validators import Regexp 验 ...

  8. springmvc中的数据传递

    import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; impo ...

  9. vue-resource对比axios import ... from和import {} from 的区别 element-ui

    1.vue-resource对比axios 文章1 文章2 1.0 axios  params 配置参数在url 显示,form-data 用于 图片上传.文件上传 1.1 axios 全局配置 ax ...

  10. 【maven】IDEA:存在jar包,pom.xml文件没报错,但是Maven-Project-Dependencies有红线报错

    1.这个问题很简单 把pom.xml里这些出错的jar包的引用先删除,再刷新一次,再添上,就行了 2.大概是idea有点反应迟钝