岛屿的个数
来源:互联网 发布:汽车分期付款怎么算法 编辑:程序博客网 时间:2024/06/11 18:20
给一个01矩阵,求不同的岛屿的个数。
0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。
class Coordinate { int x; int y; public Coordinate(int x, int y) { this.x = x; this.y = y; }}public class Solution { /** * @param grid a boolean 2D matrix * @return an integer */ public int numIslands(boolean[][] grid) { if (grid == null || grid.length == 0 || grid[0].length == 0) { return 0; } int n = grid.length; int m = grid[0].length; int island = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { //搜索到1,island+1,将此岛屿包含的1抹去(标记来过) if(grid[i][j]) { markByBFS(grid, i, j); island++; } } } return island; } private void markByBFS(boolean[][] grid, int x, int y) { //方向:4个方向 int[] directionX = {0, 0, -1, 1}; int[] directionY = {1, -1, 0, 0}; //BFS的套路,队列,加入根节点,根节点值抹去(标记来过) Queue<Coordinate> queue = new LinkedList<>(); queue.offer(new Coordinate(x, y)); grid[x][y] = false; while (!queue.isEmpty()) { Coordinate coor = queue.poll(); for (int i = 0; i < 4; i++) { Coordinate adj = new Coordinate( coor.x + directionX[i], coor.y + directionY[i] ); //判断是否出界 if (inBound(adj, grid)) { if (grid[adj.x][adj.y]) { grid[adj.x][adj.y] = false; queue.offer(adj); } } } } } private boolean inBound(Coordinate coor, boolean[][] grid) { int n = grid.length; int m = grid[0].length; return coor.x >= 0 && coor.x < n && coor.y >= 0 && coor.y < m; }}
0 0
- 题目:岛屿的个数
- LintCode 岛屿的个数
- LinkCode-岛屿的个数
- 岛屿的个数
- 岛屿的个数
- 岛屿的个数-lintcode
- 岛屿的个数
- 岛屿的个数
- LintCode:岛屿的个数
- 433-岛屿的个数
- 岛屿的个数
- 岛屿的个数-LintCode
- 岛屿的个数(LintCode)
- LintCode 433. 岛屿的个数
- Java实现-岛屿的个数
- 岛屿个数
- Lintcode解题笔记 - 岛屿的个数
- LintCode——岛屿的个数
- 对CPU,内存, 硬盘,指令之间的关系的理解
- 完全背包
- 蓝桥杯2016第九题答案
- 支持向量机通俗导论(理解SVM的三层境界)
- Android数据存储之使用数据库存储
- 岛屿的个数
- Lucene实践一:全文检索的基本原理
- 【MSP是什么】MSP的九个治理主题
- AndroidStdio DDMS连接夜神模拟器
- 蓝桥杯2016第八题答案
- Java中的静态多分派和动态多分派
- CSS代码缩写, 占用更少的宽带,单位和值
- Python“内部类”
- 2.26随记