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.