POJ 2386(DFS 求连通块数量)

POJ - 2386 (dfs简单应用) POJ - 2386 (dfs深度优先搜索) 题目正文: Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squ... 阅读详情


http://poj.org/problem?id=2386


每一次搜索一个W,从它开始用DFS扩展,把一个连通块中的W都变成”."。重复下去,直到再也找不到W。

注意这道题是八连通而不是四连通。


#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<iostream>
#define N 105
using namespace std;
int n, m, sum, flag;
string a[N];
const int dx[8] = {0, -1, 1, 0, -1, 1, 1, -1};
const int dy[8] = {-1, 0, 0, 1, -1, 1, -1, 1};
void dfs(int x, int y)
{
    if (a[x][y] == 'W')
    {
        a[x][y] = '.';
        for (int i = 0; i < 8; i++)
        {
            int x_ = x + dx[i];
            int y_ = y + dy[i];
            if (x_ >= 0 && x_ < n && y_ >= 0 && y_ < m && a[x_][y_] == 'W')
            dfs(x_, y_);
        }
    }
}
int main()
{
    int x, y;
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++) cin >> a[i];
    sum = 0;
    while (1)
    {
        flag = 0;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
        if (a[i][j] == 'W')
        {
            flag = 1;
            x = i;
            y = j;
            break;
        }
        if (flag == 0) break;
        dfs(x, y);
        sum++;
    }
    printf("%d\n", sum);
    return 0;
}

【代码超详解】POJ 2386 Lake Counting 数湖泊(DFS,0 ms) 一、题目描述 由于下雨,John 的农田的多个部分被水淹没。用 N × M 的长方形来表示农田,每个长方形里如果是W则代表有水,如果是.则代表没水。John 想知道农田里一共有多少块水洼。如果一个格及周围 8 格均存在水,那么认为这些水连续,视为同一块水洼。 第一行两个整数,单个空格分隔,分别为 N 、M ; 接下来 N 行,每行 M 个连续的字符,每个字符只可能是W或.,代表该方格有水或无水。 ... 阅读详情

相关推荐

模拟退火算法详细讲解(含实例python代码)

模拟退火算法详细讲解(含实例python代码)(一)模拟退火算法简介三级目录(二)模拟退火算法原理(1)基本思想(2)算法步骤(3)参数控制(三)实例分析 最近老师要求做模拟退火算法实验,看了很多博客之后感觉还是不太清楚,最后问了老师之后才搞明白。想把自己的理解写下来,帮助大家更好的理解。本篇文章是在另一篇博客的基础上加了一下自己的理解,然后又把我们在实验中的实例写下来,还有参考代码。希望大家看了之后能够加深对模拟退火算法的理解。 另一篇博客链接: 深度学习 — 模拟退火算法详解. (一)模拟退火算法简介

weixin_48241292的博客 17万+

POJ2386 Lake Counting DFS求连通块数量

题目链接:https://cn.vjudge.net/problem/POJ-2386 题意:         八连通的积水被认为是连在一起的,求出院子里有多少水洼。 分析:         采用深度优先搜索(DFS,Depth-First Search),从任意的w开始,不断把邻接的部分用'.'代替,1次DFS后与初始这个w连接的所有w就全都被替换成'.',因此直到图中不再存在W为止,总...

左云帆 317

多核系统核间通信(IPC)设计:从硬件机制到软件实现

在多核处理器与嵌入式系统设计中,核间通信(IPC)是实现计算资源协同工作的核心技术。其原理基于共享内存、硬件邮箱与中断等底层硬件机制,通过构建结构化的消息传递通道,实现核间高效、可靠的数据交换。该技术的核心价值在于打破多核间的壁垒,将分散的计算单元整合为有机整体,从而显著提升系统整体性能与响应能力。在工程实践中,IPC广泛应用于智能座舱、边缘AI网关、实时控制系统等场景,用于处理如仪表显示、AI推理、实时控制等复杂任务。本文聚焦于基于共享内存与VRING的消息队列实现,深入剖析缓存一致性、内存屏障等关键问题

weixin_27006759的博客 611

POJ2386(DFS)

POJ2386(DFS) Lake Counting Description Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water (‘W’)

shui2104的博客 225

模型参考自适应控制(MRAC):让PID参数动态优化

本文深入解析模型参考自适应控制(MRAC)技术,它通过实时调整PID参数,使控制系统能自动适应系统特性变化和外部干扰。文章详细介绍了MRAC的工作原理、数学基础,并提供了用C语言实现的实战代码示例,帮助工程师解决传统PID控制在非线性、时变系统中参数整定繁琐的难题。

tequila的博客 914

海思方案定制hi3531dv200/SS528 DVR方案解析:从硬件选型到编解码实战应用

海思方案,Hi3518EV100,Hi3518CV100,Hi3515CV100,Hi3516CV100,Hi3516ECV100,Hi3516D,Hi3516A,Hi3519,Hi3520D,Hi3521A,Hi3535,Hi3531,Hi3536,Hi3536C,Hi3536D,Hi3518EV200,Hi3518EV201,Hi3520DV200,Hi3516CV200,Hi3516CV300,Hi3516AV200,Hi3520DV300,Hi3519V101,sd3403,hi3519av200

1598

POJ2386 Lake Counting【DFS】

Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 55916 Accepted: 27265 Description Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a...

cutlery1137的博客 336

esp32 python开发环境搭建_eclipse esp32开发环境搭建

安装方法基本是按照官网提供的方法来操作https://github.com/espressif/idf-eclipse-plugin#GettingStarted但是官网的方法安装之后还是不能编译成功的,第一次编译会出现一下问题问题1:Building in: E:\eclipse-workspace\helloworlk\buildcmake -G Ninja -DCMAKE_TOOLCHAIN...

weixin_39978276的博客 1270

Lake Counting/POJ 2386/DFS

Lake Counting/POJ 2386/DFS 题目 Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) sq...

weixin_45600829的博客 162

人形机器人新产品导入(NPI)工艺工程师的角色与技术解析

本文系统解析人形机器人NPI工程师的核心职责与能力要求。主要内容包括:1)NPI工程师需主导装配工艺设计、样品试做及问题闭环,涉及公差分析(如尺寸链计算)、工艺评审与FMEA应用;2)要求输出完整工艺文档体系,并跟踪试产至量产全过程;3)任职资格强调3年以上机器人/智能制造行业经验,掌握SPC、公差计算等质量工具,熟悉点胶/焊接等工艺及特殊材料特性;4)通过实际案例展示关节精度优化、新物料验证等典型工作场景;5)提供基于职责的面试问题及技术性解答方案。文章聚焦技术细节,为从业者提供实用参考框架。

郑伟强dev的专栏 385

『OPEN3D』1.2 mesh处理 python篇

介绍open3d对mesh的基本处理操作

NNNNNathan的博客 4657

[Java] POJ 2386

思路: 求一个图中有多少个连通快即可。当发现一个点是‘W’时,从这个点出发进行dfs,将他附近8个方向上的点都标记为’.’,且又从这个8个方向(必须是‘W’)进行dfs。最终会将一个连通快全部标记为‘.’。标记一个连通块,进行ans++。最后输出有多少个连通块即可。 import java.util.Scanner; public class POJ_2386 { static char[][...

Tizzi的博客 788

5、自动化代码结构与运维系统的优化

本文探讨了自动化代码结构与运维系统的优化方法,涵盖审批流程的模块化设计、日志记录与工单系统的集成、通知方式的选择、错误处理的策略以及持续改进的实践。同时,深入分析了运维盲目性问题,通过故障案例揭示了关键指标缺失和日志未充分利用的弊端,提出了开发与运维角色转变的必要性。文章还介绍了如何生成有用的系统指标、建立良好的日志习惯以及实施日志聚合,以提升系统的可观测性和可靠性。最终通过总结和流程图展示了优化措施的核心要点,为构建高效、可靠的运维体系提供了指导。

pp12345的博客 84

POJ-2386.Lakecounting(DFS求连通块)

  本题是一道连通块的入门题,用来练手,后续还会更新连通块的题目。   本题大意:一个n * m的陆地上面有很多水洼,让你统计水洼的个数并输出。   本题思路:按照顺序遍历陆地,如果发现水洼就将它的八连块都进行探索,发现水洼就继续探索,直到一片大水洼都被探索完,就继续进行其他搜索,DFS。   代码: 1 #include <cstdio> 2 using na...

weixin_30325793的博客 120

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

【POJ 2386 --- Lake Counting】DFS

【POJ 2386 --- Lake Counting】DFS Description Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M...

来日浅谈的博客 518

深度学习工具包 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")

POJ2386 Lake Counting 深度优先搜索

poj2386 Description Due to recent rains, water has pooled in various places in Farmer John's field, which is represented by a rectangle of N x M (1 &lt;= N &lt;= 100; 1 &lt;= M &lt;= 100) squares. E...

Yerkeys的博客 230

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

POJ2386 Lake Counting

题目链接 http://poj.org/problem?id=2386 大致题意 有一个大小为N×M的园子,雨后积起了水。八连通的积水被认为是连在一起的。求园子里一共有多少水洼? . . . . W . 八连通指的就是左图中相对W的*的部分 . . . 解题思路 题目的意思是说八联通的积水算一个积水,所以只要从任意的W开始,不停的把邻接部分用.替代,1次DFS之后与初始的W连接的所有W都被替换...

Fitz的博客 301

POJ-2386 Lake Counting

DFS POJ-2386 Lake Counting 题目链接:POJ-2386 题目大意:W为水坑 水坑周围八个格内还有水坑的话极即相连的水坑(可视为同一片水坑) 问总共有多少片水坑 解题思路:DFS,遍历整个图,如果遇到水坑就进入dfs,然后往当前的点的四周扩散,将同一片的水坑W替换为空地.,看总共通过遍历调用的dfs的次数 代码块: #include<iostream> #in...

鱼头的水题之路 335

2019寒假专题一 dfs求连通块 入门题 B POJ 2386 C POJ 1979

B 题面 题面描述 分析 代码 C 题面 题面描述 分析 代码

cym_的博客 215

【POJ 2386 --- Lake Counting】

【POJ 2386 --- Lake Counting】 Description Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M &l...

来日浅谈的博客 520

POJ 2386

http://poj.org/problem?id=2386 这个题目与那个POJ 1562几乎是差不多的,只不过那个比这个输入要复杂一些 1 #include <stdio.h> 2 #include <string.h> 3 #include <iostream> 4 5 6 using namespace std...

A1823085974的博客 94

《挑战程序设计(第二版)》(第二章)POJ No.2386

POJ 2386 问题: 有一个大小为N×M的园子,雨后积起了水。八连通的积水被认为是连在一起的。求园子里一共有多少水洼?\ 限制条件N,M<=100 输入 W........WW. .WWW.....WWW ....WW...WW. .........WW. .........W.. ..W......W.. .W.W.....WW. W.W.W.....W. .W.W......W. ..W.......W. 输出: 3 题解: DFS次数为水洼的个数, POJ No.2386 py

Spaceack的专栏 236

【题解】POJ 2386 LakeCounting(DFS)

POJ 2386 LakeCounting 原题 Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) square...

bu_shushu的博客 465

搜索 dfs POJ 2386

http://poj.org/problem?id=2386 POJ 2386 dfs #include<cstdio> #include<cstring> #include<string> #include<iostream> #include<stack> #include<queue> using namespace s...

Hepburn_Sunsir的博客 267

POJ.2386 Lake Counting

DFS POJ.2386Lake CountingSample inputSample output Lake Counting Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= ...

想喝奶茶的胖大海 333

POJ 2386(DFS)

深度优先搜索属于图算法的一种,英文缩写为DFS即Depth First Search.其过程简要来说是对每一个可能的分支路径深入到不能再深入为止,而且每个节点只能访问一次. 举例说明之:下图是一个无向图,如果我们从A点发起深度优先搜索(以下的访问次序并不是唯一的,第二个点既可以是B也可以是C,D),则我们可能得到如下的一个访问过程:A->B->E(没有路了!回溯到A)-&g...

aocang4831的博客 412
上一篇: POJ 题目分类
下一篇: POJ 3669 Meteor Shower(BFS)
Muya77
博客等级 码龄11年 1粉丝 82原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址