Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 785 · Bipartite / 2-Coloring

Is Graph Bipartite?

LeetCode 785 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

BFS 2-colouring per component.

நடுத்தரம்Depth-First SearchBreadth-First SearchUnion-FindGraph TheoryGraph Coloring
LeetCode இல் திற ↗

நான் 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. 1

    colors = −1 for uncoloured.

  2. 2

    For every uncoloured node, BFS from it with colour 0.

  3. 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.