【发布时间】:2020-06-18 19:22:53
【问题描述】:
考虑一个有 N 行 M 列的矩阵,其中每个单元格包含“0”或“1”,任何包含 1 的单元格都称为填充单元格。如果两个单元在水平、垂直或对角线上彼此相邻,则称它们是连接的。如果一个或多个填充单元相连,它们就形成一个区域。任务是找到最大区域的单位面积。
这是我的代码:
class GFG {
static int max;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int t = 0; t < T; t++) {
max = 1;
int R = sc.nextInt();
int C = sc.nextInt();
int[][] M = new int[R][C];
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
M[i][j] = sc.nextInt();
}
}
printMatrix(M, R, C);
boolean[][] visited = new boolean[R][C];
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
int L = 1;
if (M[i][j] == 1 && !visited[i][j])
markVisited(M, visited, i, j, R, C, L);
}
}
System.out.println(max);
}
}
private static void printMatrix(int[][] M, int R, int C) {
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
System.out.print(M[i][j] + " ");
}
System.out.println();
}
}
public static boolean isSafe(int[][] M, boolean[][] visited, int i, int j, int R, int C) {
return ((i >= 0 && i < R) && (j >= 0 && j < C) && (M[i][j] == 1 && (!visited[i][j])));
}
public static void markVisited(int[][] M, boolean[][] visited, int x, int y, int R, int C, int L) {
// int[] x_pos = {1 , 1, 1, 0, 0, -1, -1, -1};
// int[] y_pos = {-1, 0, 1, -1, 1, -1, 0, 1};
//commenting the arrays, as selecting one of the above and below combinations, result in different outputs
int[] x_pos = { -1, -1, -1, 0, 0, 1, 1, 1 };
int[] y_pos = { -1, 0, 1, -1, 1, -1, 0, 1 };
visited[x][y] = true;
for (int k = 0; k < 8; k++) {
if (isSafe(M, visited, x + x_pos[k], y + y_pos[k], R, C)) {
L++;
max = Math.max(L, max);
markVisited(M, visited, x + x_pos[k], y + y_pos[k], R, C, L);
}
}
}
}
代码不适用于下面提到的测试用例:
1
4 7
1 1 1 1 0 0 1 1 0 1 0 1 1 0 0 0 0 0 1 0 1 1 0 0 0 1 1 1
输出为 13,预期为 14。
有趣的是,如果我将 markVisited 方法中的 x_pos 和 y_pos(在代码中注释)更改为
int[] x_pos = {1 , 1, 1, 0, 0, -1, -1, -1};
int[] y_pos = {-1, 0, 1, -1, 1, -1, 0, 1};
输出为 14。我不明白当 x_pos 和 y_pos 组合相同时输出如何变化。
它也发生在其他测试用例中。我评论了 x_pos[] 和 y_pos[]。
请提出问题所在。
【问题讨论】:
标签: java algorithm graph depth-first-search breadth-first-search