Skip to content

Commit 16c7777

Browse files
authored
Update and rename 261. Graph Valid Tree.md to 261._Graph_Valid_Tree.md
1 parent 24aa1b6 commit 16c7777

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

docs/Leetcode_Solutions/Python/261. Graph Valid Tree.md renamed to docs/Leetcode_Solutions/Python/261._Graph_Valid_Tree.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,54 @@ class Solution:
6868
return len(set(find(i) for i in uf)) == 1 # fully connected
6969
```
7070

71+
> 思路 2
72+
******- 时间复杂度: O(V + E)******- 空间复杂度: O(V)******
7173

74+
- DFS判断是否从起始点可以走完所有点(是否完全联通)
75+
- 中间碰到一个点,除了它来自的那个点(prev_v)以外,它其余的所有neghbor都应该是没有被访问过的(否则有环)
7276

77+
beats 36.01%
7378

79+
```python
80+
class Graph(object):
81+
def __init__(self, vertex_cnt):
82+
self.vertex_cnt = vertex_cnt
83+
self.graph = collections.defaultdict(list)
84+
85+
def addEdge(self, v1, v2):
86+
self.graph[v1].append(v2)
87+
self.graph[v2].append(v1)
88+
89+
def hasCycleHelper(self, v, visited, prev_v):
90+
self.visited[v] = True
91+
for i in self.graph[v]:
92+
if not visited[i]:
93+
if self.hasCycleHelper(i, visited, v):
94+
return True
95+
else:
96+
if i != prev_v:
97+
return True
98+
return False
99+
100+
def hasCycle(self):
101+
self.visited = [False] * self.vertex_cnt
102+
if self.hasCycleHelper(0, self.visited, -1):
103+
return True
104+
return False
105+
106+
107+
class Solution:
108+
def validTree(self, n, edges):
109+
"""
110+
:type n: int
111+
:type edges: List[List[int]]
112+
:rtype: bool
113+
"""
114+
graph = Graph(n)
115+
for node1, node2 in edges:
116+
graph.addEdge(node1, node2)
117+
return not graph.hasCycle() and all(graph.visited)
118+
```
74119

75120

76121

0 commit comments

Comments
 (0)