0

Given a Matrix consisting of 0s and 1s. Find the number of islands of connected 1s present in the matrix. Note: A 1 is said to be connected if it has another 1 around it (either of the 8 directions).

I have written code as mentioned below:

class Islands {

    // Function to find the number of island in the given list A
    // N, M: size of list row and column respectively
    static boolean isSafe(int i, int j, ArrayList<ArrayList<Boolean>> visited, int R, int C,ArrayList<ArrayList<Integer>> A){
        return ((i>=0 && i<R) && (j>=0 && j<C) && (A.get(i).get(j)==1) && (!visited.get(i).get(j)));
    }
    static void BFS(ArrayList<ArrayList<Integer>> A,ArrayList<ArrayList<Boolean>> visited,int x , int y){
        int[] x_pos = {-1,-1,-1,0,0,1,1,1};
        int[] y_pos = {-1,0,1,-1,1,-1,0,1};
        visited.get(x).add(y,true);
        for(int k=0;k<8;k++){
            if(isSafe(x+x_pos[k],y+y_pos[k],visited,A.size(),A.get(0).size(),A))
                BFS(A,visited,x+x_pos[k],y+y_pos[k]);
        }
    }
    
    static int findIslands(ArrayList<ArrayList<Integer>> A, int N, int M) {
        ArrayList<ArrayList<Boolean>> visited = new ArrayList<>();
        for(int i=0;i<N;i++) {
            visited.add(i,new ArrayList<Boolean>(M));
        }
        for(int i=0;i<N;i++){
            for(int j=0;j<M;j++){
                visited.get(i).add(j,false);
            }
        }
        int num = 0;
        for(int i=0;i<N;i++){
            for(int j=0;j<M;j++){
                if((A.get(i).get(j)==1) && (!visited.get(i).get(j))){
                    BFS(A, visited,i,j);
                    num++;
                }
            }
        }
        return num;
        
    }
}

For TestCase

1 1 0

0 0 1

1 0 1

Its returning 3 instead of 2.

While debugging, I found visited array getting modified like this

true true false

false false true

false false true

true true false

false false true

true false false

true true false

false false true

true false true

What I don't understand is which part of my code changing the value true to false(Highlighted one). Please suggest.

Community
  • 1
  • 1

1 Answers1

1

Class ArrayList<E>

public void add(int index, E element)

Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

See the documentation

What happens is that in fact you push the values at the end, and go from

true true false

false false true

false false true

to

true true false

false false true

true false false true
One Lyner
  • 1,964
  • 1
  • 6
  • 8