Saturday 20 April 2024

Detect a cycle in an undirected graph using dfs

import java.util.*;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World");
        int V = 5;  // Adjust the number of vertices appropriately
        HashMap<Integer, ArrayList<Integer>> adj = makeAdjList(V);
        addEdge(0, 2, adj);
        addEdge(0, 1, adj);
        addEdge(0, 3, adj);
        addEdge(2, 4, adj);
        addEdge(4, 1, adj);
       
        System.out.println(adj);
        System.out.println("The graph has cycle: " + isCycle(V, adj));
    }

    public static boolean dfs(int node, int parent, HashMap<Integer,
ArrayList<Integer>> adj, boolean[] vis) {
        vis[node] = true;
        for (int it : adj.get(node)) {
            if (!vis[it]) {
                if (dfs(it, node, adj, vis)) {
                    return true;
                }
            } else if (it != parent) {
                return true;
            }
        }
        return false;
    }

    public static boolean isCycle(int V, HashMap<Integer,
ArrayList<Integer>> adj) {
        boolean[] vis = new boolean[V];
        for (int i = 0; i < V; i++) {
            if (!vis[i]) {
                if (dfs(i, -1, adj, vis)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static HashMap<Integer, ArrayList<Integer>>
makeAdjList(int V) {
        HashMap<Integer, ArrayList<Integer>> adj = new HashMap<>();
        for (int i = 0; i < V; i++) {
            adj.put(i, new ArrayList<Integer>());
        }
        return adj;
    }

    public static void addEdge(int src, int dest,
HashMap<Integer, ArrayList<Integer>> adjList) {
        adjList.get(src).add(dest);
        adjList.get(dest).add(src);
    }
}

 

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...