Design a linear time algorithm for each of the following problem: (1) given a graph G, test if G is connected. (2) given a graph G, test if G is a tree. (3) given a graph G, test if G has a cycle,if so,print a cycle
实例如下:
import numpy
from numpy import *
def dfs( v ):
vis[v] = -1
flag = 0
for i in range(n):
# print (a[v][i],'---', vis[i] )
if a[v][i] != 0 and vis[i] != -1:
dfs(i)
vis[i] = 1
else:
pass
if a[v][i] != 0 and vis[i] == -1:
print ('Yes
剑指Offer(Python多种思路实现):环的入口节点
面试23题:
题目:如果一个链表中包含环,如何找出环的入口节点?
解题分析:其实此题可以分解为三个题目:1)如何判断一个链表中是否包含环?2)如何找到环的入口节点?3)如何得到环中节点的数目?
解题思路一:可以设置两个指针,一快一慢。
def detectCycle(self, head):
fast = slow = head
# 检测是否有环
while fast and fast.next: