Posts

Showing posts from August, 2022

A Java Program to detect cycle in a graph

class GFG { private final int V ; private final List<List<Integer>> adj ; public GFG ( int V) { this . V = V ; adj = new ArrayList<>(V) ; for ( int i = 0 ; i < V ; i++) adj .add( new LinkedList<>()) ; } // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212 private boolean isCyclicUtil ( int i , boolean [] visited , boolean [] recStack) { // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; List<Integer> children = adj .get(i) ; for (Integer c: children) if (isCyclicUtil(c , visited , recStack)) return true; recStack[i] = false; return false; } private void addE...

js newbie "A" wants to learn React from "B" and wants to know in his newtwork who can introduce him to B in the shortest time period.

  Input format: Total Members in UI friend Network = N MemberId1 = N1 MemberId2 = N2 MemberId3 = N3 MemberIdN = Nn Output format: shortest time A takes to reach B Sample Input: 4 2 5 7 9 4 2 9 2 7 2 3 7 9 7 9 5 1 7 9 Sample Output: 5 Solution:3 public class Graph { static class Node { private String name ; private List<Node> shortestPath = new LinkedList<>() ; private Integer distance = Integer. MAX_VALUE ; Map<Node , Integer> adjacentNodes = new HashMap<>() ; public void addDestination (Node destination , int distance) { adjacentNodes .put(destination , distance) ; } public Node (String name) { this . name = name ; } // getters and setters public String getName () { return name ; } public void setName (String name) { this . name = name ; } public List<Node> getShortestPath () { ...