1 Star 0 Fork 0

Neo_1001/LeetCode刷题记录

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
LC_695.java 2.11 KB
Copy Edit Raw Blame History
Neo_1001 authored 2024-04-10 22:16 . first commit
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);
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/neo1001/leet-code-practice-record.git
git@gitee.com:neo1001/leet-code-practice-record.git
neo1001
leet-code-practice-record
LeetCode刷题记录
master

Search