leedcode面试题 16.19. 水域大小求助帖

有大佬可以帮我看一下我的代码哪里有问题吗,我觉得我的代码和题解的bfs的思想是一样的,但是总过不了第二个

class Main{

static LinkedList<Integer> list = new LinkedList<>();

static int[] x3 = {-1, 0, 1, 0, -1, 1, 1, -1};

static int[] y3 = {0, -1, 0, 1, -1, -1, 1, 1};

public static void bfs(int[][] land, int[][] visited, int y, int x) {

Queue<int[]> que = new LinkedList<>();

que.add(new int[]{y, x});

visited[y][x] = 1; // 标记初始节点为已访问

int count = 0;

while (!que.isEmpty()) {

int[] arr = que.poll();

int y1 = arr[0];

int x1 = arr[1];

for (int i = 0; i < 8; i++) {

int x2 = x1 + x3[i];

int y2 = y1 + y3[i];

if (x2 >= 0 && x2 < land[0].length && y2 >= 0 && y2 < land.length && visited[y2][x2] == 0 && land[y2][x2] == 0) {

que.add(new int[]{y2, x2});

visited[y2][x2] = 1; // 立即标记为已访问

count++;

}

}

}

list.add(count + 1); // 包含初始节点

}

public static int[] pondSizes(int[][] land) {

int n = land.length;

int m = land[0].length;

int[][] visited = new int[n][m];

// 设置访问数组,全部没有被访问过

for (int i = 0; i < n; i++) {

Arrays.fill(visited[i], 0);

}

for (int i = 0; i < n; i++) {

for (int j = 0; j < m; j++) {

if (land[i][j] == 0 && visited[i][j] == 0) {

bfs(land, visited, i, j);

}

}

}

int[] arr = new int[list.size()];

for (int i = 0; i < list.size(); i++) {

arr[i] = list.get(i);

}

Arrays.sort(arr);

return arr;

}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值