【LeetCode】Number of Islands

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

算法思想

问题类似于图的遍历问题,我们假设每一个点都是顶点,利用图的优先搜索算法,进行遍历。

1. 每次选择一个点,并且访问这个点的4上下左右四个方向上的点,直到访问完所有的临接点。

2. 每次重新选择点就是一个新的岛的存在。

算法实现

public class Solution {
    boolean[][] visitPoint = null;
    int cols=0,rows=0;
    public void visitIsland(char[][] grid, int i, int j) {
        visitPoint[i][j]=true;
        if(i-1>=0&&visitPoint[i-1][j]==false&&grid[i-1][j]==‘1‘)
            visitIsland(grid,i-1,j);
        if(i+1<rows&&visitPoint[i+1][j]==false&&grid[i+1][j]==‘1‘)
            visitIsland(grid,i+1,j);
        if(j-1>=0&&visitPoint[i][j-1]==false&&grid[i][j-1]==‘1‘)
            visitIsland(grid,i,j-1);
        if(j+1<cols&&visitPoint[i][j+1]==false&&grid[i][j+1]==‘1‘)
            visitIsland(grid,i,j+1);
    }

    public int numIslands(char[][] grid) {
        if(grid==null)
            return 0;

        rows = grid.length;
        if(rows==0)
            return 0;

        cols = grid[0].length;

        visitPoint = new boolean[rows][cols];
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                visitPoint[i][j]=false;
            }
        }
        int num = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (visitPoint[i][j] == false && grid[i][j] == ‘1‘) {
                    num++;
                    visitIsland(grid, i, j);
                }
            }

        }
        return num;
    }
}

算法时间

T(n)=O(n2)

演示结果

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class SolutionTest {
    private Solution s = new Solution();

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testNumIslands() {
        char[][] grid3 = {
                { ‘1‘, ‘1‘, ‘0‘, ‘0‘, ‘0‘ },
                { ‘1‘, ‘1‘, ‘0‘, ‘0‘, ‘0‘},
                { ‘0‘, ‘0‘, ‘1‘, ‘0‘, ‘0‘ },
                { ‘0‘, ‘0‘, ‘0‘, ‘1‘, ‘1‘}
        };
        assertEquals(3,s.numIslands(grid3));

        char[][] grid1 = {
                { ‘1‘, ‘1‘, ‘1‘, ‘1‘, ‘0‘ },
                { ‘1‘, ‘1‘, ‘0‘, ‘1‘, ‘0‘},
                { ‘1‘, ‘1‘, ‘0‘, ‘0‘, ‘0‘ },
                { ‘0‘, ‘0‘, ‘0‘, ‘0‘, ‘0‘}
        };
        assertEquals(1,s.numIslands(grid1));

        char[][] grid = {};
        assertEquals(0,s.numIslands(grid));
        assertEquals(0,s.numIslands(null));
    }

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-07-29 07:03:43

【LeetCode】Number of Islands的相关文章

【LeetCode】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 surrounde

【leetcode】Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should retu

【leetcode】Number of 1 Bits (easy)

做太多遍了,秒杀. class Solution { public: int hammingWeight(uint32_t n) { int num = 0; for(;n; n &=(n-1), num++); return num; } };

【LeetCode】BFS(共43题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [101]Symmetric Tree 判断一棵树是不是对称. 题解:直接递归判断了,感觉和bfs没有什么强联系,当然如果你一定要用queue改写的话,勉强也能算bfs. // 这个题目的重点是 比较对象是 左子树的左儿子和右子树的右儿子, 左子树的右儿子和右子树的左儿子.不要搞错. // 直接中序遍历的话会有错的情况,最蠢的情况是数字标注改一改.. 1 /** 2

【LeetCode】并查集 union-find(共16题)

链接:https://leetcode.com/tag/union-find/ p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [128]Longest Consecutive Sequence  (2018年11月22日,开始解决hard题) 给了一个无序的数组,问这个数组里面的元素(可以重新排序)能组成的最长的连续子序列是多长.本题的时间复杂度要求是 O(N). 本题 array 专题里面有, 链接:https

【LeetCode】深搜DFS(共85题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [98]Validate Binary Search Tree [99]Recover Binary Search Tree [100]Same Tree [101]Symmetric Tree [104]Maximum Depth of Binary Tree [105]Construct Binary Tree from Preorder and Inorder

LeetCode | 0200. Number of Islands岛屿数量【Python】

LeetCode 0200. Number of Islands岛屿数量[Medium][Python][DFS] Problem LeetCode 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 v

【LeetCode】Single Number (2 solutions)

Single Number Given an array of integers, every element appears twice except for one. Find that single one. Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 解法一:用map记录每个元素的次数,返回次数为1的元素 cl

【LeetCode】 Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6. More practice: If you have figu