Friday 19 April 2024

Cycle detection in Graph via BFS

import java.util.*;

class Pair<Key, Value> {
    public Key first;
    public Value second;

    public Pair(Key first, Value second) {
        this.first = first;
        this.second = second;
    }
}
public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        HashMap<Integer, ArrayList<Integer>> adjList = new HashMap<>();

        // Adding nodes to the graph
        for (int i = 0; i <= 8; i++) {
            adjList.put(i, new ArrayList<>());
        }

        // Adding edges to the graph
        addEdge(adjList, 1, 2);
        addEdge(adjList, 1, 3);
        addEdge(adjList, 3, 4);
        addEdge(adjList, 3, 6);
        addEdge(adjList, 6, 8);
        addEdge(adjList, 7, 5);
        addEdge(adjList, 2, 5);

        // Print the adjacency list
        System.out.println("Adjacency List: " + adjList);
        System.out.println("The graph has cycle: true/false ?");
        //ArrayList < Integer > ans = bfsOfGraph(7, adjList);
        //int n = ans.size();
        /*for(int i = 0;i<n;i++) {
            //System.out.print(ans.get(i)+" ");
           
        }*/
        System.out.println(isCycle(8,adjList));
    }
   
    public static boolean isCycle(int V, HashMap<Integer, ArrayList<Integer>> adjList)
    {
        boolean vis[] = new boolean[V+1];
        Arrays.fill(vis,false);
        for(int i=0;i<V;i++)
        {
            if(vis[i] == false)
            {
                if(bfsOfGraph(i, vis, V,adjList)) return true;
            }
        }
        return false;
    }
   
    public static boolean bfsOfGraph(int src, boolean vis[], int V, HashMap<Integer, ArrayList<Integer>> adjList) { // V is last number(max num) of graph
        //ArrayList < Integer > bfs = new ArrayList < > ();
        //boolean vis[] = new boolean[V+1];
        Queue <Pair<Integer,Integer>> q = new LinkedList < > ();
        q.add(new Pair(src,-1));
        vis[src] = true;
        while (!q.isEmpty()) {
            int node = q.peek().first;
            int parent = q.peek().second;
            q.poll();
            //bfs.add(node);
            for (int it: adjList.get(node)) {
                if (vis[it] == false) {
                    vis[it] = true;
                    q.add(new Pair(it,node));
                }
                else if(parent != it) return true;
            }
        }

        return false;
    }
   
   
    // Helper method to add an edge to the graph
    public static void addEdge(HashMap<Integer, ArrayList<Integer>> adjList, int source, int destination) {
        adjList.get(source).add(destination);
        adjList.get(destination).add(source); // If the graph is undirected
    }
}

No comments:

Post a Comment

Good thoughtful question on Binary search on answers

Problem link:  https://leetcode.com/problems/maximize-score-of-numbers-in-ranges/description/ Solution: //import java.util.Arrays; class So...