Матрица в java fix - PullRequest
       8

Матрица в java fix

0 голосов
/ 21 июня 2020

Мой код должен go по всем индексам матрицы. И посчитайте, сколько существует разделов числа 1. Например: введите здесь описание изображения

  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;
}

Судя по моему отпечатку, он действительно меняет все 1-е числа, но на выходе получается 1, а не 3, как должно быть.

это выход

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

число 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

1 Ответ

0 голосов
/ 21 июня 2020

Попробуйте это.

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();
}

и

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...