掘金团队号上线,助你 Offer 临门! 点击 查看详情
一、题目描述:
Given an m x n 2d grid map of '1's (land) and '0's (water), return the number of islands which the sum of 1‘s on the island equal S (S>0).
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
], S = 9
Output: 1
public int sumIslands(char[][] grid, int S){
// implementation
}
//----------
// unit test
//----------
Tip: using Junit4.
public void sumIslandsTest(){
char[][] grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
];
int S = 8;
// test implementation
}
二、思路分析:
岛屿问题的小变种,从算有几个岛屿变成算岛屿多大。
一次完整的dfs
- 判断退出条件(非法或合法)
- 记录已访问
- return 递归其他点
这里非法指越界,合法指已经遍历过该点
三、AC 代码:
package com.company;
public class * {
public int sizer;
public int sizel;
public int sumIslands(char[][] grid, int S){
// implementation
this.sizer = grid.length;
this.sizel = grid[0].length;
int ret = 0;
for (int i = 0; i < grid.length; i++){
for (int j = 0; j < grid[0].length; j++){
int tmp = dfs(grid, i, j);
if(tmp == S)ret++;
}
}
return ret;
}
public int dfs(char[][] grid, int r, int l){
//非法
if(r >= sizer || r < 0 || l < 0 || l >= sizel){
return 0;
}
//不是岛屿或已经遍历
if(grid[r][l] != 1){
return 0;
}
grid[r][l] = 2;
return 1 + dfs(grid,r + 1, l)+ dfs(grid,r , l + 1)+ dfs(grid,r - 1, l)+ dfs(grid,r, l - 1);
}
//----------
// unit test
//----------
// Tip: using Junit4.
public void sumIslandsTest(){
char[][] grid = {
{'1', '1', '1', '1', '0'},
{'1', '1', '0', '1', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '0', '0', '0'}
};
int S = 8;
// test implementation
// 由于S = 8,而岛屿等于9 因此返回0
System.out.println(sumIslands(grid,S));
}
public static void main(String[] args) {
* v = new *();
v.sumIslandsTest();
}
}
四、总结:
由于一直对回溯,递归的抵触,导致我每次遇到这类题都想着位运算,并查集的骚套路,为此吃了不少亏,希望各位不要走我老路。