Untitled

mail@pastecode.io avatar
unknown
java
6 months ago
1.1 kB
1
Indexable
Never
import java.util.ArrayList;

public class MaxNodesCovered {
    public static int findStartingNode(int[] B) {
        int N = B.length;
        int maxNodes = 0;
        int startingNode = 1; // Default starting node is 1 (1-based indexing)

        for (int i = 1; i <= N; i++) {
            int currentNode = i;
            boolean[] visited = new boolean[N + 1]; // Visited array for DFS
            int nodesCovered = 0;

            while (!visited[currentNode]) {
                visited[currentNode] = true;
                currentNode = B[currentNode - 1]; // Adjust for 1-based indexing

                nodesCovered++;
            }

            if (nodesCovered > maxNodes) {
                maxNodes = nodesCovered;
                startingNode = i;
            }
        }

        return startingNode;
    }

    public static void main(String[] args) {
        int[] B = {2, 3, 4, 1, 5}; // Example input
        int startingNode = findStartingNode(B);
        System.out.println("Starting Node: " + startingNode);
    }
}