abhaysinghr516 / Algorithms

This repository contains a collection of various algorithms implemented in C, C++, Go, Java, JavaScript, and Python. The goal of this repository is to help fellow programmers learn and understand algorithms more effectively by providing code examples and explanations in multiple programming languages.
MIT License
9 stars 26 forks source link

Union Find Algorithm in Python #92

Open abhaysinghr516 opened 10 months ago

alok5050 commented 10 months ago

Hey, I would like to work on this issue.

alok5050 commented 10 months ago

def initialize(n): global Arr, size for i in range(n + 1): Arr[i] = i size[i] = 1

def find(i): global Arr, size

while (Arr[i] != i):
    Arr[i] = Arr[Arr[i]] # Skip one level 
    i = Arr[i] # Move to the new level
return i

def _union(xr, yr): global Arr, size if (size[xr] < size[yr]): # Make yr parent of xr Arr[xr] = Arr[yr] size[yr] += size[xr] else: # Make xr parent of yr Arr[yr] = Arr[xr] size[xr] += size[yr]

def isCycle(adj, V): global Arr, size

for i in range(V):
    for j in range(len(adj[i])):
        x = find(i) # find root of i 
        y = find(adj[i][j]) # find root of adj[i][j] 

        if (x == y):
            return 1 # If same parent 
        _union(x, y) # Make them connect
return 0

MAX_VERTEX = 101

Arr = [None] * MAX_VERTEX

size = [None] * MAX_VERTEX

V = 3

adj = [[] for i in range(V)]

adj[0].append(1) adj[0].append(2) adj[1].append(2)

if (isCycle(adj, V)): print("Graph contains Cycle.") else: print("Graph does not contain Cycle.")

abhaysinghr516 commented 10 months ago

Create Pull Request

nazishkn67 commented 10 months ago

Hey Abhay, I would like to work on this issue if currently, no one is working on this.