ball-blog
  • Welcome, I'm ball
  • Machine Learning - Basic
    • Entropy
    • Cross Entropy
    • KL-Divergence
    • Monte-Carlo Method
    • Variational Auto Encoder
    • SVM
    • Adam Optimizer
    • Batch Normalization
    • Tokenizer
    • Rotary Positional Encoding
    • Vector Quantized VAE(VQ-VAE)
    • DALL-E
    • Diffusion Model
    • Memory Layers at Scale
    • Chain-of-Thought
  • Einsum
  • Linear Algebra
    • Linear Transformation
    • Determinant
    • Eigen-Value Decomposition(EVD)
    • Singular-Value Decomposition(SVD)
  • AI Accelerator
    • CachedAttention
    • SGLang
    • CacheBlend
  • Reinforcement Learning
    • Markov
  • Policy-Improvement Algorithm
  • Machine Learning - Transformer
    • Attention is All you need
    • Why do we need a mask in Transformer
    • Linear Transformer
    • kr2en Translator using Tranformer
    • Segment Anything
    • MNIST, CIFAR10 Classifier using ViT
    • Finetuning PaliGemma using LoRA
    • LoRA: Low-Rank Adaptation
  • EGTR: Extracting Graph from Transformer for SGG
  • Machine Learning - Mamba
    • Function Space(Hilbert Space)
    • HIPPO Framework
    • Linear State Space Layer
    • S4(Structures Space for Sequence Model)
    • Parallel Scan Algorithm
    • Mamba Model
  • Computer System
    • Memory Ordering: Release/Acquire 1
    • Memory Ordering: Release/Acquire 2
    • BUDAlloc
    • Lock-free Hash Table
    • Address Sanitizer
  • App development
    • Bluetooth connection in linux
    • I use Bun!
    • Using Tanstack-query in Frontend
    • Deploying AI Service using EC2
  • Problem Solving
    • Bipartite Graph
    • Shortest Path Problem in Graph
    • Diameter of a Tree
  • Scribbles
Powered by GitBook
On this page
  • Definition of Bipartite Graph data-structure
  • Checking if it is Bipartite Graph

Was this helpful?

Edit on GitHub
  1. Problem Solving

Bipartite Graph

Last updated 3 months ago

Was this helpful?

Definition of Bipartite Graph data-structure

Let's say you are coloring the graph nodes. You cannot color neighboring nodes with same color. If you can color the entire graph with only two colors, then the graph is defined as Bipartite Graph .

Bipartite Graph data-structure is used to express functions like X→YX \to YX→Y.

Checking if it is Bipartite Graph

We can check if the given graph is Bipartite Graph using BFS, DFS graph-search algorithm.

In this post, I will use DFS algorithm.

I used DFS algorithm to color every nodes in the island. If every node in island is colored, then we move to the next island.

from collections import deque


class Graph:
    def __init__(self, V, E):
        self.V = V
        self.E = E
        self.data = dict()

    def add_edge(self, u, v):
        if u not in self.data:
            self.data[u] = [v]
        else:
            self.data[u].append(v)

        if v not in self.data:
            self.data[v] = [u]
        else:
            self.data[v].append(u)

    def neighbors(self, u):
        if u not in self.data:
            return []
        else:
            return self.data[u]
    
    def is_bipartite(self):
        # check if graph is bipartite using BFS algorithm
        is_visited = dict()


        # set vertex 1 as visited
        # number 0 means colored red
        # number 1 means colored blue

        for v in range(1, self.V+1):
            
            # use DFS to color all the island
            if v not in is_visited:
                next_to_color = deque()
                next_to_color.append((v, True))

                while len(next_to_color) != 0:
                    coloring_node, color = next_to_color.popleft()
                    if coloring_node not in is_visited:
                        is_visited[coloring_node] = color 
                    
                    # case if already colored
                    elif is_visited[coloring_node] == color:
                        continue 
                    else:
                        return False 

                    # add neighbor node of coloring_node to next_to_color 
                    for neighbor in self.neighbors(coloring_node):
                        next_to_color.append((neighbor, not color))
            else:
                pass 

        return True 

def main():
    K = int(input())
    # print(K)

    for _ in range(K):
        V, E = [int(x) for x in input().split()]
        graph = Graph(V, E)

        for _ in range(E):
            u, v = [int(x) for x in input().split()]
            graph.add_edge(u, v)
                       
        
        if graph.is_bipartite():
            print("YES")
        else:
            print("NO")
        


if __name__ == "__main__":
    main()

Following code is solution for problem.

Baekjoon:#1707
Bipartite Graph expressing X→YX \to YX→Y function