There was an error while loading. Please reload this page.
1 parent 0ee512b commit 95357faCopy full SHA for 95357fa
1 file changed
leetcode3/최원준/785. Is Graph Bipartite?.py
@@ -0,0 +1,45 @@
1
+#
2
+
3
+'''
4
+1. 아이디어 :
5
+Bipartite는 그래프에서 노드들을 2가지 색을 칠했을때, 인접한 노드와 다른 색일때 성립.
6
+bfs를 통해 노드들의 색갈을 0 또는 1로 칠한다.
7
+그래프가 끊긴 문제는 모든 노드들을 순회하게끔 한다.
8
9
+2. 시간복잡도 :
10
+ O(V + E) 노드, 간선
11
12
+3. 자료구조/알고리즘 :
13
+BFS
14
15
16
+class Solution:
17
+ def isBipartite(self, graph: List[List[int]]) -> bool:
18
+ n = len(graph)
19
+ colors = [-1] * n
20
21
+ for i in range(n):
22
+ if colors[i] != -1:
23
+ continue
24
25
+ colors[i] = 0
26
+ queue = deque()
27
+ queue.append(i)
28
29
+ while queue:
30
+ start = queue.popleft()
31
+ start_color = colors[start]
32
33
+ for dest in graph[start]:
34
+ dest_color = colors[dest]
35
+ if start_color == dest_color:
36
+ return False
37
38
+ if dest_color == -1:
39
+ queue.append(dest)
40
+ colors[dest] = (1 + start_color) % 2
41
+ # print(colors)
42
+ return True
43
44
45
0 commit comments