Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 7aea795

Browse files
committed
#695 岛屿最大面积
1 parent 384af52 commit 7aea795

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package DFS_BFS;
2+
3+
/**
4+
* @author liangqian0723@gmail.com
5+
* @since 2020/3/16 11:49 AM
6+
*/
7+
public class LC_695_AaxAreaOfIsland {
8+
int[] dx = new int[]{1, -1, 0, 0};
9+
int[] dy = new int[]{0, 0, 1, -1};
10+
11+
/**
12+
* 沉岛解法: 如果一个格子是岛屿,将岛屿沉掉,并遍历该格子前后左右(4通)的格子是否为岛屿,并且沉掉,直到将所有的岛屿都沉了
13+
*/
14+
public int maxAreaOfIsland(int[][] grid) {
15+
int maxArea = 0;
16+
17+
for (int i = 0; i < grid.length; i++) {
18+
for (int j = 0; j < grid[0].length; j++) {
19+
if (grid[i][j] == 1) {
20+
int hasSink = sink(i, j, grid);
21+
maxArea = Math.max(hasSink, maxArea);
22+
}
23+
}
24+
}
25+
return maxArea;
26+
}
27+
28+
private int sink(int i, int j, int[][] grid) {
29+
int hasSink = 1;
30+
grid[i][j] = 0;
31+
for (int k = 0; k < dx.length; ++k) {
32+
int m = i + dx[k];
33+
int n = j + dy[k];
34+
if (m < 0 || m >= grid.length || n < 0 || n >= grid[0].length) {
35+
continue;
36+
}
37+
if (grid[m][n] == 1) {
38+
hasSink += sink(m, n, grid);
39+
}
40+
}
41+
return hasSink;
42+
}
43+
44+
45+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package DFS_BFS;
2+
3+
import org.junit.Test;
4+
5+
import static org.hamcrest.core.Is.is;
6+
import static org.junit.Assert.assertThat;
7+
8+
/**
9+
* @author liangqian0723@gmail.com
10+
* @since 2020/3/16 11:48 AM
11+
*/
12+
public class LC_695_AaxAreaOfIslandTest {
13+
@Test
14+
public void test_mac_area_of_island() {
15+
LC_695_AaxAreaOfIsland aol = new LC_695_AaxAreaOfIsland();
16+
assertThat(aol.maxAreaOfIsland(new int[][]{
17+
{0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
18+
{0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
19+
{0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
20+
{0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0},
21+
{0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0},
22+
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0},
23+
{0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
24+
{0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}
25+
}), is(6));
26+
}
27+
}

0 commit comments

Comments
 (0)