GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/java/695_Max_Area_of_Island.java at master · godspeedz/leetcode

Expand file tree

/

695_Max_Area_of_Island.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
57 lines (55 loc) · 1.95 KB
/

695_Max_Area_of_Island.java

Copy path

File metadata and controls

57 lines (55 loc) · 1.95 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*class Solution {
int[][] grid;
public int area(int r, int c) {
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] == 0)
return 0;
grid[r][c] = 0;
return (1 + area(r + 1, c) + area(r - 1, c)
+ area(r, c - 1) + area(r, c + 1));
}
public int maxAreaOfIsland(int[][] grid) {
this.grid = grid;
int ans = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
ans = Math.max(ans, area(r, c));
}
}
return ans;
}
}*/
class Solution {
// DFS and you can implement BFS with queue
public int maxAreaOfIsland(int[][] grid) {
int[] dr = new int[]{1, -1, 0, 0};
int[] dc = new int[]{0, 0, 1, -1};
int ans = 0;
for (int r0 = 0; r0 < grid.length; r0++) {
for (int c0 = 0; c0 < grid[0].length; c0++) {
if (grid[r0][c0] == 1) {
int shape = 0;
Stack<int[]> stack = new Stack();
stack.push(new int[]{r0, c0});
grid[r0][c0] = 0;
while (!stack.empty()) {
int[] node = stack.pop();
int r = node[0], c = node[1];
shape++;
for (int k = 0; k < 4; k++) {
int nr = r + dr[k];
int nc = c + dc[k];
if (0 <= nr && nr < grid.length &&
0 <= nc && nc < grid[0].length &&
grid[nr][nc] == 1) {
stack.push(new int[]{nr, nc});
grid[nr][nc] = 0;
}
}
}
ans = Math.max(ans, shape);
}
}
}
return ans;
}
}
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.