Is Graph Bipartite?
LeetCode 785 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
BFS 2-colouring per component.
నేను Is Graph Bipartite? (LeetCode 785) ను ఇలా పరిష్కరించాను — Bipartite / 2-Coloring ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Try to 2-colour the graph: colour a node, give all its neighbours the other colour, and continue with BFS. If you ever find an edge with both ends the same colour, it isn't bipartite.
Approach
- 1
colors = −1 for uncoloured.
- 2
For every uncoloured node, BFS from it with colour 0.
- 3
Neighbours get 1 − colour; same colour → False.
నేను ఎలా పరిష్కరించాను
BFS colouringPythonO(V+E) time
class Solution:
def isBipartite(self, graph: List[List[int]]) -> bool:
#check if two adjacent nodes has the same color or not
n = len(graph)
colors = [-1]*n
def bfs(start):
q = deque([start])
colors[start]=0
while q:
node = q.popleft()
for adj_node in graph[node]:
if colors[adj_node]==-1:#no color yet
colors[adj_node]=1-colors[node] #if currenr node color is 0 then 1 else 1-1 i.e 0
q.append(adj_node)
elif colors[adj_node]==colors[node]:
return False
return True
for i in range(n):
if colors[i]==-1:
if not bfs(i):
return False
return True
Is Graph Bipartite? — తరచూ అడిగే ప్రశ్నలు
Is Graph Bipartite? వెనుక ఉన్న intuition ఏమిటి?
Try to 2-colour the graph: colour a node, give all its neighbours the other colour, and continue with BFS. If you ever find an edge with both ends the same colour, it isn't bipartite.
Is Graph Bipartite? (LeetCode 785) ను ఎలా పరిష్కరించాలి?
1. colors = −1 for uncoloured. 2. For every uncoloured node, BFS from it with colour 0. 3. Neighbours get 1 − colour; same colour → False.
Is Graph Bipartite? యొక్క time, space complexity ఎంత?
Time: O(V + E). Space: O(V). (Accepted approach: BFS colouring.)
Is Graph Bipartite? లో సాధారణ పొరపాట్లు ఏమిటి?
The graph can be disconnected — start a BFS from every uncoloured node.