博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Number of Islands
阅读量:4073 次
发布时间:2019-05-25

本文共 1867 字,大约阅读时间需要 6 分钟。

Number of Islands

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. 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:

11110 11010 11000 00000

Answer: 1

Example 2:

11000 11000 00100 00011

Answer: 3

Java代码:

public class Solution {    public int numIslands(char[][] grid) {         if (grid == null || grid.length == 0) {	            return 0;	        }	        int rowLen = grid.length;	        int colLen = grid[0].length;	        boolean[][] visited = new boolean[rowLen][colLen];	        int[][] direct = new int[][]{
{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; Deque
queue = new ArrayDeque<>(); int res = 0; for (int i = 0; i < rowLen; i++) { for (int j = 0; j < colLen; j++) { if (!visited[i][j] && grid[i][j] == '1') { res++; queue.add(i * colLen + j); while (!queue.isEmpty()) { int pos = queue.poll(); int curr_x = pos / colLen; int curr_y = pos % colLen; if (visited[curr_x][curr_y]) { continue; } visited[curr_x][curr_y] = true; for (int k = 0; k < 4; k++) { int x = curr_x + direct[k][0]; int y = curr_y + direct[k][1]; if (x >= 0 && y >= 0 && x < rowLen && y < colLen && grid[x][y] == '1') { queue.add(x * colLen + y); } } } } } } return res; }}

转载地址:http://fvuni.baihongyu.com/

你可能感兴趣的文章
SQL语句(二)查询语句
查看>>
SQL语句(六) 自主存取控制
查看>>
《计算机网络》第五章 运输层 ——TCP和UDP 可靠传输原理 TCP流量控制 拥塞控制 连接管理
查看>>
堆排序完整版,含注释
查看>>
二叉树深度优先遍历和广度优先遍历
查看>>
生产者消费者模型,循环队列实现
查看>>
PostgreSQL代码分析,查询优化部分,process_duplicate_ors
查看>>
PostgreSQL代码分析,查询优化部分,canonicalize_qual
查看>>
PostgreSQL代码分析,查询优化部分,pull_ands()和pull_ors()
查看>>
IA32时钟周期的一些内容
查看>>
获得github工程中的一个文件夹的方法
查看>>
《PostgreSQL技术内幕:查询优化深度探索》养成记
查看>>
PostgreSQL查询优化器详解之逻辑优化篇
查看>>
STM32中assert_param的使用
查看>>
C语言中的 (void*)0 与 (void)0
查看>>
vu 是什么
查看>>
io口的作用
查看>>
IO口的作用
查看>>
UIView的使用setNeedsDisplay
查看>>
归档与解归档
查看>>