gpt4 book ai didi

java - 求 boolean 矩阵中最大区域的长度

转载 作者:行者123 更新时间:2023-12-02 01:18:50 30 4
gpt4 key购买 nike

我有一个类(class),他们计算矩阵中最大的“1”岛,但他的岛概念是“如果两个单元在水平、垂直或对角线上彼此相邻,则称它们是相连的。 “

我需要帮助来删除对角台阶。

class GFG {
static int ROW, COL, count;

static boolean isSafe(int[][] M, int row,
int col, boolean[][] visited) {
return ((row >= 0) && (row < ROW) && (col >= 0)
&& (col < COL) && (M[row][col] == 1 &&
!visited[row][col]));
}

static void DFS(int[][] M, int row,
int col, boolean[][] visited) {
int[] rowNbr = {-1, -1, -1, 0, 0, 1, 1, 1};
int[] colNbr = {-1, 0, 1, -1, 1, -1, 0, 1};

visited[row][col] = true;

for (int k = 0; k < 8; k++) {
if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) {
count++;
DFS(M, row + rowNbr[k], col + colNbr[k], visited);
}
}
}

static int largestRegion(int[][] M) {
boolean[][] visited = new boolean[ROW][COL];
int result = 0;
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
if (M[i][j] == 1 && !visited[i][j]) {
DFS(M, i, j, visited);
result = Math.max(result, count);
}
}
}
return result;
}

public static void main(String args[]) {
int M[][] = {{0, 0, 1, 1},
{1, 0, 1, 1},
{0, 1, 0, 0},
{0, 0, 0, 0}};
ROW = 4;
COL = 4;
System.out.println(largestRegion(M));
}
}

打印的响应是 6,但我需要他返回 4 我现在已经尝试了所有方法,但无法解决。算法原帖:https://www.geeksforgeeks.org/find-length-largest-region-boolean-matrix/

最佳答案

只需将邻居数组的坐标更改为4即可。

int rowNbr[] = { -1, 0, 0, 1}; 
int colNbr[] = { 0, -1, 1, 0};

迭代四次

 for (int k = 0; k < 4; ++k) 

The updated code:

关于java - 求 boolean 矩阵中最大区域的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58120957/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com