Search code examples
algorithmgraph-algorithmdepth-first-searchrecursive-backtracking

Memory limit exceeded in DFS algorithm


I implemented this code.

But unfortunately it becomes "time limit exceeded".

The algorithm for finding the path from the first A[0][0] to the last A[n][n] two-dimensional array.

I used the "DFS" algorithm.

import javax.jnlp.IntegrationService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class prj{
static boolean[] dfs(byte[][]A,boolean[]v,int num,int start){
    v[start]=true;
    if(start==num-1){
        return v;
    }
    for (int i = 0; i < num; i++) {
        if (A[start][i]==1&&v[i]==false){
            dfs(A,v,num,i);
        }
    }
    return v;
}
public static void main(String[] args) {
    Scanner scanner=new Scanner(System.in);
    int n=scanner.nextInt();
    int m=scanner.nextInt();
    byte[][] A=new byte[n][n];
    for (int i = 0; i <m ; i++) {
        int v=scanner.nextInt();
        int u=scanner.nextInt();
        A[v-1][u-1]=1;
    }
   
    boolean visited[]=new boolean[n];
    
    if(A[0][n-1]==1){
        System.out.println("YES");
    }else {
        visited = dfs(A, visited, n, 0);
        boolean b = true;
        for (int i = 0; i < n; i++) {
            if (visited[i] == false) {
                System.out.println("NO Path");
                b = false;
                break;
            }
        }
        if (b == true) {
            System.out.println("YES ,Path  exists ");
        }
     }
  }
}

Solution

  • You have to clarify what is the boundary of n and m.
    However I guess that in this question m would be much smaller than than n * n.
    If it's the case, instead of creating a n * n array, you can define a hash table with m elements, with each element has pair of (v, u) as key, and "is it visited" as boolean value.

    Map<Pair<Integer, Integer>, Boolean> nodes = new Hashtable<>();
    for (int i = 0; i <m ; i++) {
        int v=scanner.nextInt();
        int u=scanner.nextInt();
        nodes.put(new Pair(v, u), false);
    }
    

    Cause reading and writing in a hash table has constant time complexity, it's not different from defining a n * n array, in time complexity, but much more memory efficient.