您的位置:首页 > 编程语言 > Java开发

leetcode-200-岛屿的个数 (number of islands)-java

2018-11-21 09:54 447 查看
版权声明:此文章为许诗宇所写,如需转载,请写下转载文章的地址 https://blog.csdn.net/xushiyu1996818/article/details/84313721

题目及测试

[code]package pid200;
/*  岛屿的个数

给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。

示例 1:

输入:
11110
11010
11000
00000

输出: 1

示例 2:

输入:
11000
11000
00100
00011

输出: 3

*/

import java.util.List;

public class main {

public static void main(String[] args) {
char[][] testTable = {{'1','1','0','0','0'},{'1','1','0','0','0'},
{'0','0','1','0','0'},{'0','0','0','1','1'}};
test(testTable);
}

private static void test(char[][] ito) {
Solution solution = new Solution();
int rtn;
long begin = System.currentTimeMillis();
for(char[] now:ito){
for(char nowc:now){
System.out.print(nowc+" ");
}
System.out.println();
}
System.out.println();
//开始时打印数组

rtn= solution.numIslands(ito);//执行程序
long end = System.currentTimeMillis();

System.out.println("rtn=" );
System.out.print(rtn);

System.out.println();
System.out.println("耗时:" + (end - begin) + "ms");
System.out.println("-------------------");
}

}

自己没想出来

解法1(别人的)

采用深度优先遍历,把访问过的改为‘0’,继续遍历

[code]public class 岛屿的数量 {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0
|| grid[0].length == 0)
return 0;
int rows = grid.length;
int cols = grid[0].length;
int count = 0;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
// 注意char
if (grid[i][j] == '1') {
count++;
dfsSearch(grid, i, j, rows, cols);
}
return count++;
}

// 每遇到'1'后, 开始向四个方向 递归搜索. 搜到后变为'0',
// 因为相邻的属于一个island. 然后开始继续找下一个'1'.
private void dfsSearch(char[][] grid,
int i, int j, int rows, int cols) {
if (i < 0 || i >= rows || j < 0 || j >= cols)
return;
if (grid[i][j] != '1')
return;
// 也可以才用一个visited数组,标记遍历过的岛屿
grid[i][j] = '0';
dfsSearch(grid, i + 1, j, rows, cols);
dfsSearch(grid, i - 1, j, rows, cols);
dfsSearch(grid, i, j + 1, rows, cols);
dfsSearch(grid, i, j - 1, rows, cols);

}
}

 

 

 

 

 

 

 

 

 

 

 

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: