Fetch the repository succeeded.
package LeetCode;
import java.util.ArrayDeque;
import java.util.Deque;
public class LC_695 {
static Deque<int[]> deque = new ArrayDeque<>();
static int[][] move = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
static int max = 0;
public static void main(String[] args) {
int[][] grid = {
{0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
{0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0},
{0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}
};
System.out.println(maxAreaOfIsland(grid));
}
public static int maxAreaOfIsland(int[][] grid) {
boolean[][] visited = new boolean[grid.length][grid[0].length];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1 && !visited[i][j]) {
deque.offer(new int[]{i, j});
visited[i][j] = true;
bfs(grid,visited);
}
}
}
return max;
}
public static void bfs(int[][] grid,boolean[][] visited) {
int cont = 1;
while (!deque.isEmpty()) {
int x = deque.getFirst()[0];
int y = deque.getFirst()[1];
deque.removeFirst();
for (int i = 0; i < move.length; i++) {
int nextx = x + move[i][0];
int nexty = y + move[i][1];
if (nextx < 0 || nextx > grid.length - 1 || nexty < 0 || nexty > grid[0].length - 1) continue;
else {
if (grid[nextx][nexty] == 1 && !visited[nextx][nexty]) {
cont++;
deque.add(new int[]{nextx, nexty});
visited[nextx][nexty] = true;
}
}
}
max = Math.max(cont, max);
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。