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.