Leetcode-Number of Islands

leetcode解题之200. Number of Islands Java版(岛屿的数量) leetcode解题之200. Number of Islands Java版(岛屿的数量) ,深度优先遍历 阅读详情

今天看到Leetcode又有新题,故着手去做。题目比较简单,就是dfs或bfs的应用。

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.

题意:给定一个2维的网格地图,地图上为字符“1”或“0”,其中“1”为陆地,“0”为水域,默认地图周围都是由水构成。相连的陆地算作一个岛屿,求出地图中的岛屿总数。比如:

11110

11010

11000

00000

为1个岛屿。

11000

11000

00100

00011

为3个岛屿。

分析:只需要对每一个陆地区域做一次dfs,每次dfs中将已经遍历的陆地网格“1”变为水域网格“0”(防止再次遍历导致重复)。对每次dfs计数,总共dfs的次数即为岛屿总数。应注意,grid为空的特殊情况应该排除。

AC代码:

class Solution {
public:
    int numIslands(vector<vector<char>> &grid) {
        int row = grid.size();
        if (!row) return 0;
        int col = grid[0].size();
        int count = 0;

        for (unsigned i = 0; i != row; ++i) {
        	for (unsigned j = 0; j != col; ++j) {
        		if (grid[i][j] == '1') {
        			dfs(grid, i, j); ++count;
        		}
        	}
        }

        return count;
    }
    void dfs(vector<vector<char>> &grid, unsigned i, unsigned j) {
    	int dx[4] = {1, 0, -1, 0};
    	int dy[4] = {0, 1, 0, -1};
    	int row = grid.size(), col = grid[0].size();
    	grid[i][j] = '0';

    	for (int k = 0; k != 4; ++k) {
    		int new_i = i + dx[k], new_j = j + dy[k];
    		if (new_i >=0 && new_i < row && new_j >= 0 && new_j < col && grid[new_i][new_j] == '1')
    			dfs(grid, new_i, new_j);
    	}
    }
};
如代码或分析有误,请批评指正,谢谢!




华为OD机试 - 最佳对手(Python/JS/C/C++ 2025 A卷 200分) 本专栏收录于《华为OD机试真题(Python/JS/C/C++)》。刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新。游戏里面,队伍通过匹配实力相近的对手进行对战。但是如果匹配的队伍实力相差太大,对于双方游戏体验都不会太好。给定n个队伍的实力值,对其进行两两实力匹配,两支队伍实例差距在允许的最大差距d内,则可以匹配。要求在匹配队伍最多的情况下,匹配出的各组实力差 阅读详情

相关推荐

Verilog实现FIR滤波器

1、FIR滤波器简介 不追究FIR滤波器的深层含义,我们只关注如何实现;可以看出,FIR滤波器的本质就是延迟、系数相乘与求和,如下图: 2、设计 基于以上分析,按照三级流水实现FIR滤波器设计:信号延迟-系数相乘-求和 `timescale 1ns / 1ps module fir( input clk, input rst_n, input [3:0]din, output reg [9:0]dout ); // data reg reg [3:0]din1; reg [3:.

CLL_caicai的博客 1万+

【Leetcode】Number of Islands

题目链接:https://leetcode.com/problems/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 co

业精于勤,荒于嬉 1000

【C++】小猫钓鱼纸牌游戏--C++实现

小猫钓鱼问题: 描述:初始,两个人各有n张牌(牌面0-10),顺序固定,只能按顺序出牌。然后,两个人轮流在桌面上以接龙的方式出牌,当某个人放置的牌在桌面上已经出现时,他收起相同牌面及其中间的牌作为自己的筹码,同时需要再放一张牌到桌面。某人手上的牌出完后,另一个人继续出,直到两人手上都没牌为止,输出结束时两个人手上的筹码数。 #include<iostream> using namespace std; struct queue { int head; //队列首 int tail; //

qq_41344430的博客 3202

[leetcode] 305. Number of Islands II 解题报告

题目链接: https://leetcode.com/problems/number-of-islands-ii/ A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at posi

小榕流光的专栏 5062

小程序 video 控制器外观调整_Kessil 360X Tuna Sun无线控制器使用分享

之前分享了Kessil 360X Tuna Sun开箱记录,时间关系,没来得及使用WiFi Dongle无线控制器。昨晚抽空实操了一下,做个操作记录,希望对大家有参考Kessil无线模块操作指南官方视频英文教程配中文字幕,非常详尽语速较快,重点位置可以暂停操作点击边框调出视频工具条1、拆包取控制器,保存二维码Kessil WiFi Dongle包装打开包装就能看到Kessil无线控制模...

weixin_39759060的博客 4732

Godot 4.x 实现 JRPG 回合制战斗系统:架构、状态机与实战优化

游戏开发中,状态机是管理复杂逻辑流转的核心设计模式,尤其在回合制战斗这类事件驱动的场景中。其原理是通过定义有限的状态和明确的转移条件,来控制系统在不同阶段的行为,从而实现清晰、可维护的流程控制。这项技术的价值在于能够将杂乱的条件判断代码结构化,降低模块间的耦合度,提升代码的可读性和可扩展性。在游戏开发领域,状态机广泛应用于角色AI、UI流程、战斗系统等场景。本文以Godot引擎为例,深入探讨如何运用节点与信号驱动架构,构建一个健壮的JRPG(日式角色扮演游戏)回合制战斗系统。内容涵盖从核心的**状态机**设

weixin_33749242的博客 499

Leetcode 305. Number of Islands II (python)

Leetcode 305. Number of Islands II题目:解法:hashmap 题目: 解法:hashmap 这道题是number of islands的follow up,关于number of islands见另外一篇博客。 这道题目的难点在于,

qq_37821701的博客 1211

RNA 8. SCI文章中差异基因表达--热图 (heatmap) 进阶:从数据标准化到多维度注释

本文深入探讨了RNA差异基因表达分析中热图(heatmap)的进阶应用,从数据标准化到多维度注释。详细介绍了FPKM标准化、Z-score转换等关键技术,以及pheatmap包的高级注释功能,帮助研究者制作发表级热图。文章还提供了视觉优化策略和生物学意义衔接的实用建议,助力SCI论文的数据可视化。

weixin_29051149的博客 301

LeetCode200. Number of Islands 基础dfs

题目:https://leetcode.com/problems/number-of-islands/description/ dfs寻找联通区域个数,使用递归会超时,要用栈模拟递归,代码如下: class Solution { public: void dfs(vector> grid,vector> &visited ,int i,int j){

浅时光_XinLee 543

全网最全-DA14531-全球最小-BLE从入门到精通开发教程

本教程主要适用于低功耗产品,DA14531它体积小,非常适用于对体积敏感的设备,如无线可穿戴、传感器、助听器等设备。本文经过作者发大量时间来记录开发项目的调试方法,里面有许多笔者开发心得体会,旨在让读者工程师快速上手,减少摸索时间,提高软件质量。读者对象本文档主要适用以下工程师:嵌入式系统工程师单片机软件工程师IOT固件工程师BLE固件工程师。

hejinwu1314的博客 5137

linux系统宝塔服务器temp文件夹里总是被上传病毒php脚本

服务器时不时的会发送短信说你服务器有病毒,找到了这个tmp文件,删除了之后又有了。确实是有很多人就这么无聊,每天都攻击你的服务器。找了很久的原因,网上也提供了一大堆方法,但都是很简陋的答案,具体怎么操作并没有说。没办法只能自己去排查这个问题。从两个角度来考虑,第一是服务器系统问题,比如宝塔的漏洞。但一时半会看不出问题来。只能去排查自己的项目代码。最后了解到代码确实是存在漏洞的。但代码中也确实了很多的校验,为什么会存在漏洞了?这就不得不从上传的过程开始说起。

guiplan 1496

Leetcode200. Number of Islands

一个二维数组,把 1 看做陆地,把 0 看做大海,陆地相连组成一个岛屿。把数组以外的区域也看做是大海,问总共有多少个岛屿。

magic_jiayu的博客 188

37、基于铁电场效应晶体管(FeFET)的片上深度神经网络(DNN)直接反馈对齐训练

本文提出了一种基于铁电场效应晶体管(FeFET)的深度神经网络(DNN)训练加速器架构,结合直接反馈对齐(DFA)算法和FeFET的独特物理特性,以解决当前DNN训练中反向传播(BP)算法带来的高计算开销、复杂数据依赖和高能耗问题。通过设计基于FeFET的MVM引擎、低功耗ADC和随机数生成器(RNG),该架构在速度和功率效率方面相比现有基于ReRAM的加速器分别提升了1.3倍和2.5倍。研究为未来高效能AI训练硬件的发展提供了新的思路和实现路径。

wine的专栏 162

Leetcode 200. Number of Islands

Leetcode 200. 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 horizontal...

qwfand的博客 168

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

LeetCode 200. Number of Islands 题解

本题是图论中连通分量计数的经典问题。遍历网格,找到未访问的陆地使用 DFS 或 BFS 标记整个岛屿统计岛屿数量。

cannonjinx的博客 1005

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

LeetCode 200. Number of Islands(dfs)

题目来源:https://leetcode.com/problems/number-of-islands/ 问题描述 200.Number of Islands Medium Given a 2d grid map of'1's (land) and'0's (water), count the number of islands. An island is surrounded b...

da_kao_la的博客 207

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

LeetCode刷题:200. Number of Islands

LeetCode刷题:200. Number of Islands 原题链接:https://leetcode.com/problems/number-of-islands/description/ Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands. An island is sur...

梅森上校的博客 业精于勤荒于嬉,形成于思毁于随。 702

LeetCode 200. Number of Islands--c++ dfs解法

LeetCode 200. Number of Islands LeetCode题解专栏:LeetCode题解 我做的所有的LeetCode的题目都放在这个专栏里,大部分题目Java和Python的解法都有。 Given a 2d grid map of '1’s (land) and '0’s (water), count the number of islands. An island i...

个人博客 995

[LeetCode]200. Number of Islands

https://leetcode.com/problems/number-of-islands/ 判断有多少相连的岛屿。 解法一:dfs,每次遇到1就把它置为0 public class Solution { int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; public int numIslands(c

gqk289的专栏 237

【LeetCode with JavaScript】 200. Number of Islands

原题网址:https://leetcode.com/problems/number-of-islands 难度:Medium 题目 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...

zwkkkk1的博客 776

[LeetCode][JavaScript]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 ...

weixin_30813225的博客 100

Leetcode Number of Islands

题目地址:https://leetcode.com/problems/number-of-islands/ 题目分析: 需要找出水平或者垂直相连的‘1’的个数,第一思路是递归遍历直到上下左右走没有‘1’返回,同时需要注意遍历到一个‘1’将其修改为‘0’表示已经访问过了;然后每遍历完一次即表示一个island,设置一个计数器记录遍历次数即可。 题目解答: public class Sol...

weixin_34114823的博客 108

[LeetCode]Number of Islands

原题链接:https://leetcode.com/problems/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 connec...

weixin_30394251的博客 92

leetcode Number of Islands

题目连接 https://leetcode.com/problems/number-of-islands/ Number of Islands Description Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands. An island is surrounded by w...

weixin_30466421的博客 75

[LeetCode] Number of Islands II 岛屿的数量之二

A 2d grid map ofmrows andncolumns is initially filled with water. We may perform anaddLandoperation which turns the water at position (row, col) into a land. Given a list ...

weixin_33928137的博客 437

LeetCode题解–200. Number of Islands

链接LeetCode题目:https://leetcode.com/problems/number-of-islands/难度:Medium题目 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 form

sinat_14867719的博客 480
上一篇: python实现清华大学联网助手(三)——linux下带参数的自定义命令/import机制
下一篇: Leetcode201-Bitwise AND of Numbers Range
coderhuhy
博客等级 码龄12年 24粉丝 40原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值