Leetcode岛屿数量(C++)

https://leetcode-cn.com/explore/learn/card/queue-stack/217/queue-and-bfs/872/

题目描述

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

样例1

输入:
11110
11010
11000
00000
输出: 1

样例2

输入:
11000
11000
00100
00011
输出: 3

解题思路

要求:没有被访问过且值为‘1’

依次访问每个方格,如果该方格要求,则将该方格设置为被访问过,并将该方格x、y坐标加入队列,然后获取其上下左右方格位置,符合要求也将x、y坐标加入队列。按照队列顺序依次访问方格。

这里使用了BFS(以二叉树为例,逐层遍历节点),此处提供模板:

/**
 * Return the length of the shortest path between root and target node.
 */
int BFS(Node root, Node target) {
   
    Queue<Node> queue;  // store all nodes which are waiting to be processed
    Set<Node> used;     // store all the used nodes
    int step = 0;       // number of steps neeeded from root to current node
    // initialize
    add root to queue;
    add root to used;
    // BFS
    while (queue is not empty) {
   
        step = step + 1;
        // iterate the nodes which are already in the queue
        int size = queue.size();
        for (int i = 0; i < size; ++i) {
   
            Node cur = the first node in queue;
            return step if cur is target;
            for (Node next : the neighbors of cur) {
   
                if (next is not in used) {
   
                    add next to queue;
                    add next to 
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值