undertale
undertale

Reputation: 452

count sections of one in the matrix (java)

My code should go over all the indexes of a matrix. And count how many sections of the number 1 exist. For example:enter image description here

  public static int count(int mat[][])
{
    return count(mat,0,0,0);

}

public static int count(int mat[][],int row, int col,int sum)
{
    if(row < 0 || row >= mat.length || col < 0 || col >= mat[row].length)
    {
        return sum;
    }

    if(mat[row][col] == 1)
    {
        mat[row][col] = -1;
        sum++;
        delit(mat,row,col,0);
    }

    col++;
    if(col >= mat[row].length)
    {
        row +=1;
        col = 0;
    }
    count(mat,row,col,sum);
    
    return sum;
}

public static int delit(int mat[][],int row, int col, int flag)
{   
    if(row < 0 || row >= mat.length || col < 0 || col >= mat[row].length)
    {
        return 1;
    }

    if((mat[row][col] == 0 || mat[row][col] == -1) && flag == 1)
    {
        return 1;
    }
    flag = 1;
    if( mat[row][col] == 1)
    {
        mat[row][col] = -1;
    }
    
    delit(mat,row+1,col,1);
    delit(mat,row-1,col,1);
    delit(mat,row,col+1,1);
    delit(mat,row,col-1,1);
    return 1;
}

By my print, it really does change all of the 1st numbers But the output is 1 and not 3 as it should be.

this is the out put

0 0 0 0 1

0 1 1 1 0

0 0 1 1 0

1 0 0 0 0

1 1 0 0 0

the num is 0

0 0 0 0 -1

0 -1 -1 -1 0

0 0 -1 -1 0

-1 0 0 0 0

-1 -1 0 0 0

how can i fix that?

Upvotes: 2

Views: 153

Answers (1)

user4910279
user4910279

Reputation:

Try this.

static int count(int[][] mat) {
    return new Object() {
        int height = mat.length;
        int width = mat[0].length;

        int count() {
            int count = 0;
            for (int row = 0; row < height; ++row)
                for (int col = 0; col < width; ++col)
                    if (mat[row][col] == 1) {
                        ++count;
                        delit(row, col);
                    }
            return count;
        }

        void delit(int row, int col) {
            if (row < 0 || row >= height) return;
            if (col < 0 || col >= width) return;
            if (mat[row][col] != 1) return;
            mat[row][col] = -1;
            delit(row - 1, col);
            delit(row + 1, col);
            delit(row, col - 1);
            delit(row, col + 1);
        }

    }.count();
}

and

int[][] mat = {
    {0, 0, 0, 0, 1},
    {0, 1, 1, 1, 0},
    {0, 0, 1, 1, 0},
    {1, 0, 0, 0, 0},
    {1, 1, 0, 0, 0},
};
System.out.println(count(mat));
// -> 3

Upvotes: 3

Related Questions