计算矩阵中1的节数(java)
我的代码应该检查矩阵的所有索引。 数一数数字1中有多少部分。 例如: 数字是0计算矩阵中1的节数(java),java,matrix,Java,Matrix,我的代码应该检查矩阵的所有索引。 数一数数字1中有多少部分。 例如: 数字是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 我怎样才能解决这个问题?试试这个 static int count(int[][] mat) { return new Object() { int height = mat.length; int width = mat[0].length;
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
我怎样才能解决这个问题?试试这个
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();
}
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
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