Improve runtime execution

Viewed 36

i have a block of code i need to improve because i go over the execution time suggested:

public class terace {
    public boolean trapRainWater(int[][] arr,int i,int j,int m,int n, int[][] visited){
        if(i<=0 || i>=m+1 || j<=0 || j>=n+1){
            return true;
        }

        if(visited[i][j]==1){
            return true;
        }

        visited[i][j]=1;
        
        boolean top=false,bottom=false,left=false,right=false;
        if(arr[i][j]==arr[i-1][j])

            bottom = trapRainWater(arr,i-1,j,m,n,visited);
        else if(arr[i][j]<arr[i-1][j]){
            bottom = true;
        }
        if(arr[i][j] == arr[i+1][j])
            top = trapRainWater(arr,i+1,j,m,n,visited);
        else if(arr[i][j]<arr[i+1][j]){
            top = true;
        }
        if(arr[i][j] == arr[i][j-1])
            left = trapRainWater(arr,i,j-1,m,n,visited);
        else if(arr[i][j]< arr[i][j-1]){
            left = true;
        }
        if(arr[i][j] == arr[i][j+1])
            right = trapRainWater(arr,i,j+1,m,n,visited);
        else if(arr[i][j]<arr[i][j+1]){
            right = true;
        }
        return (top && bottom && left && right);
    }
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int[][] arr = new int[m+2][n+2];
        int max = 0;
        for(int i=1;i<m+1;i++){
            for(int j=1;j<n+1;j++){
                arr[i][j] = sc.nextInt();
                if(arr[i][j]>max)
                    max = arr[i][j];
            }
        }
        for(int i=0;i<m+2;i++){
            for(int j=0;j<n+2;j++){
                if(i==0 || j==0 || i==m+1 || j==n+1)
                    arr[i][j] = max+1;
            }
        }

        int count=0;

        terace t = new terace();
        for(int i=1;i<m+1;i++){
            for(int j=1;j<n+1;j++){
                int[][] visited = new int[m+2][n+2];
                if(t.trapRainWater(arr, i, j, m, n,visited)){
                    count = count+1;       
                }
            }
        }
        System.out.println(count);


    }
}

This calculates all the positions that water can't flow lower. The code works and gives the expected output, but in some test cases it goes over. Is there anything i could change to improve the execution time? Thanks for your help in advance.

0 Answers
Related