Search code examples
javaarraysarraylistindexingsize

How to get the size of an index in an arraylist?


I am working on a code, it's mostly done, just having an issue with these two lines and i'll be done. What is the correct way to do this? I think I'm getting Arrays and ArrayLists mixed up, help please

    private final int MAX = 100000;
    private ArrayList<Integer> adj = new ArrayList(MAX);
    private boolean[] visited = new boolean[MAX];

    private void dfsFirst(int u) {
        if (visited[u]) {
            return;
        }

        visited[u] = true;

        for (int i = 0; i < adj[u].size(); i++) {   //issue here with adj
            dfsFirst(adj[u].get(i));                //issue here with adj
        }
        s.push(u);
    }

Here is the original code I am trying to translate to Java https://www.geeksforgeeks.org/2-satisfiability-2-sat-problem/


Solution

  • In the reference C++ implementation of Kosaraju's algorithm, adj must be an array of lists of integers:

    vector<int> adj[MAX]; 
    vector<int> adjInv[MAX]; 
    

    Thus, in Java it should be:

    private final int MAX = 100000;
    private List<Integer>[] adj = new List[MAX];
    private boolean[] visited = new boolean[MAX];
    private Stack<Integer> s = new Stack<>();
    
    private void dfsFirst(int u) {
        if (visited[u]) {
            return;
        }
    
        visited[u] = true;
    
        for (int i = 0; i < adj[u].size(); i++) {   // getting size of the list at `u`
            dfsFirst(adj[u].get(i));               
        }
        s.push(u);
    }