LeetCode 419. Battleships in a Board 题解(C++)

项目二:用C++做一个战舰游戏 project(battleships) set(CMAKE_CXX_STANDARD 11) add_executable(battleships battleships.cpp player.h player.cpp) #include"player.h" int main(){ // std::array<std::array<int,10>10> gri... 阅读详情

LeetCode 419. Battleships in a Board 题解(C++)


题目描述

  • Given an 2D board, count how many different battleships are in it. The battleships are represented with ‘X’s, empty slots are represented with ‘.’s. You may assume the following rules:
  • You receive a valid board, made of only battleships or empty slots.
  • Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
  • At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.

举例

  • Example:
    X..X
    …X
    …X
    In the above board there are 2 battleships.
  • Invalid Example:
    …X
    XXXX
    …X
    This is not a valid board - as battleships will always have a cell separating between them.

思路

  • 这里需要计算战舰队的数量count,可转换为计算每个战舰队位于最左上角的船只(我们称为战舰队头)。
  • 用两个循环,对网格内的每一个格子进行遍历,若该格子为X(即有战舰),则分以下几种情况:
    若在网格的最左上角(即i=0,j=0),则存在一个舰队,count自加1;
    若在网格的最上角(即i=0),但不在最左边(即j!=0),则需要判断该位置的左边(即board[i][j-1])是否有战舰存在,若其左边不存在战舰,则该位置为战舰队头,count自加1;
    若在网格的最左边(即j=0),但不在最上边(即i!=0),则需要判断该位置的上面(即board[i-1][j])是否有战舰存在,若其上面不存在战舰,则该位置为战舰队头,count自加1;
    若战舰不在最左边也不在最上边(即i!=0且j!=0),则需要判断该战舰的左边和上面是否还有战舰存在,若其左边和上面都不存在战舰,则该位置为战舰队头,count自加1;
    其余情况,战舰都不属于战舰队头。

代码

class Solution 
{
public:
    int countBattleships(vector<vector<char>>& board)
    {
        int count = 0;
        int row = board.size();
        int column = board[0].size();
        for (int i = 0; i < row; ++i)
        {
            for (int j = 0; j < column; ++j)
            {
                if (board[i][j] == 'X')
                {
                    if (i == 0 && j == 0)
                    {
                        ++count;
                    }
                    else if (i == 0 && board[i][j - 1] != 'X')
                    {
                        ++count;
                    }
                    else if (j == 0 && board[i - 1][j] != 'X')
                    {
                        ++count;
                    }
                    else if (i != 0 && j != 0 && board[i][j - 1] != 'X' && board[i - 1][j] != 'X')
                    {
                        ++count;
                    }
                }
            }
        }
        return count;
    }
};
BattleshipMiniProject #BattleshipMiniProject 立即下载

相关推荐

在Windows11上安装ubuntu版linux系统并实现桌面图形化(WSL)

在Windows11上安装ubuntu版linux系统并实现桌面图形化(WSL),xfce桌面美化、安装google-chrome

NiKoJJ‘s Blog 1万+

LeetCode每日一题 | 419 | 甲板上的战舰 |二维数组遍历

✨今天给大家带来的是LeetCode上的第419题——甲板上的战舰(✨。这道题目是一个经典的二维数组遍历问题,要求我们在一个棋盘中找到所有的战舰。接下来给大家详细讲解一下解题思路和主要的数据结构哦~🥳。

PAIN的博客 551

QDMA工程搭建/windows驱动编译与性能测试

请注意,根据您的目标操作系统,您可能需要在windows启动配置中启用测试签名的驱动程序,以便启用此驱动程序的安装。右键单击设备,选择更新驱动程序软件,然后选择构建的QDMA驱动程序的文件夹(通常为。创建一个新工程,在IP Catalog中搜索QDMA,双击创建qdma ip核。驱动程序安装安装驱动程序最简单的方法是通过Windows的“设备管理器”。如果系统提示未经验证的驱动程序发布者,请选择无论如何安装此驱动程序软件。本节主要介绍QDMA驱动在Windows系统的源文件、编译和安装过程。

qq_28455081的博客 2287

419. Battleships in a Board(C++)

原題 Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules: You receive

qq_33469427的博客 289

如何在SendWS实现WhatsApp批量群发设置管理?WhatsApp群发超链有什么好处?

WhatsApp群发顾名思义就是对WhatsApp上的用户好友进行群发消息,给他们群发想要发送的消息。及时不认识对方也可以对他进行群发超链。越来越多做跨境出海运营的工作者利用WhatsApp进行营销推广,因为他能做到低成本高回报,向客户发送消息曝光自己的品牌或产品,使得更多人了解,拓展新客户,提高成交率。

SendWS-WS云控群控拓客聊天翻译 1170

ArcGIS插值可视化气象数据

前言 地图底图的制作和气象数据的预处理见我上两篇博客 ArcGIS精美中国地图制作(详解) python处理日值气象数据 在前面我们已经将日值的地温数据处理成了年均地温,添加了站点经纬度坐标并导出为excel格式。 得到如下数据: 导入数据 在Arcmap中 文件-添加XY数据 将年均地温和站点位置数据导入。 注意:excel表格的格式要另存为97-2003工作簿形式,否则会有"arcgi...

江北20190411的博客 2万+

题解——Leetcode 419. Battleships in a Board 难度:Medium

Given an 2D board, count how many battleships are in it. The battleships are represented with'X's, empty slots are represented with '.'s. You may assume the following rules: You receive a valid bo

dxk3881345的博客 288

HFSS螺旋线圈的优化设计与高效仿真实践

本文详细介绍了HFSS螺旋线圈的优化设计与高效仿真实践,涵盖核心参数设置、参数化建模、仿真加速技巧及结果分析。通过HFSS软件实现螺旋线圈的高效仿真,特别适用于无线充电和RFID系统设计,提升设计效率与性能验证准确性。

weixin_30235225的博客 445

leetcode 419 Battleships in a Board C++

好久不刷leetcode了,因为找了个还比较满意的实习,今天突然上来发现C++都不会写了。。。还是要保持手感呐。 这道题第一思路就是DFS,然而它给了两个要求,一个是不能改变board,第二是只用O(1)的额外空间。 先说下修改board的吧。 找到一个X之后用DFS把周围的全部变成‘.’就可以了。 符合条件的解法是找到X且上边和右边都没有X,很巧妙。 代码如下,注意边界,不然就cras

wcxdell的专栏 815

DCA1000EVM数据采集实战:从mmWave Studio配置到MATLAB后处理的全链路解析

本文详细解析了DCA1000EVM数据采集的全流程,从mmWave Studio配置到MATLAB后处理,涵盖数据存储结构解析、后处理引擎剖析及Python数据处理方案。通过实战案例,帮助开发者高效处理毫米波雷达原始数据,实现从数据到应用价值的转化,提升开发效率。

weixin_33743661的博客 708

我用 AI 做了个开源地图工具:从 OpenStreetMap 一键获取全国 AOI/POI 数据

本文介绍了一款免费开源的OSM数据查询与可视化工具,旨在解决Overpass QL语法晦涩、数据获取门槛高的问题。工具支持面数据(AOI)、点数据(POI)及路网三种查询模式,内置30+常用模板实现一键检索。具备高德与OSM双底图切换、坐标自动转换功能,支持GeoJSON、SHP、CSV多格式导出,同时保留自定义查询能力。作为纯HTML单文件应用,可零成本部署至GitHub Pages在线使用。该工具有效降低了地理数据获取难度,是替代商业地图API、高效提取全球开源地理信息的实用利器。

weixin_45812624的博客 587

【LeetCode】419. Battleships in a Board 解题报告(Python & C++)

【LeetCode】419. Battleships in a Board 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/battleships-in-a-board/description/ 题目描述: Given an 2D board, count how many battleships...

负雪明烛 1613

立项书8分钟定生死?手把手教你用ChatGPT辅助打造高水平申报书,让评审专家一看就想打高分!

宏大叙事、空话堆砌只会让评审绕晕,不如聚焦一个具体问题,拿出清晰的研究路径、扎实的设计方案,把“我想做什么、为什么做、打算怎么做”讲明白。对评审来说,关键不在你读了多少,而在你能否看清领域的共识、争议和空白,GPT的作用就在于帮你理清研究脉络,发现问题结构,聚焦那些还没被充分讨论的变量或方法,去提升综述的深度。之前要用到ProcessOn、Draw.io等工具画流程图,现在有了ai虽然方便了,但也需要多次调教,如果嫌麻烦,七哥给大家准备了课题申报常用的流程图,技术路线图,方便大家直接拿来编辑填空使用。

智能AI让学术科研更容易 291

leetcode419

种子填充419 class Solution { private: int dx[4] = {0,-1,0,1}; int dy[4] = {-1,0,1,0}; public: void dfs(vector<vector<char>>& board,int r,int c) { board[r][c]...

剑似生平 274

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

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

LeetCode 419. 甲板上的战舰(C、C++、python)

给定一个二维的甲板, 请计算其中有多少艘战舰。 战舰用 'X'表示,空位用 '.'表示。 你需要遵守以下规则: 给你一个有效的甲板,仅由战舰或者空位组成。 战舰只能水平或者垂直放置。换句话说,战舰只能由 1xN (1 行, N 列)组成,或者 Nx1 (N 行, 1 列)组成,其中N可以是任意大小。 两艘战舰之间至少有一个水平或垂直的空位分隔 - 即没有相邻的战舰。 示例 : X..X ...

qq_27060423的博客 477

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

【Lintcode】986. Battleships in a Board

题目地址: https://www.lintcode.com/problem/battleships-in-a-board/description 给定一个二维矩阵,含.和X两种字符。任何一个1×N1\times N1×N或者N×1N × 1N×1的X组成的行或列视为一个“战舰”。问一共有多少个战舰。题目保证战舰与战舰之间是有一个空行或者空列的。 遍历矩阵,注意,每个战舰我们只计数其最左上角的X,这样就能保证不重不漏。代码如下: public class Solution { /** *

数学、算法爱好者的博客 223

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

leetcode 419

此题技巧题,可以通过试试几个简单的例子,能够发现结果。我们记录X出现的总次数,然后记录X四周出现的X的数目,可以发现结果就是count-repeat/2,附代码,(emmmmm果然python和C++,C#,java 这些语言没啥区别) class Solution:     def countBattleships(self, board):         """         :type...

bengepai的博客 304

[LeetCode] 419. Battleships in a Board 解题报告

Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with'.'s. You may assume the following rules: You receive a valid b

萌萌小七的专栏 654

[Leetcode] 419. Battleships in a Board 解题报告

题目: Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules: You receive

魔豆(Magicbean)的博客 378

每日一题(4.24-5.1)

目录4.27-C Mini Battleship—递归回溯4.26-I Letter Wheels—预处理标记+枚举4.25-F Hopscotch—暴力枚举4.24-D. Explorer Space—记忆化搜索orDP 4.27-C Mini Battleship—递归回溯 来源:2021年度训练联盟热身训练赛第六场——C Mini Battleship 最大55的图,最多有5支战舰队,战舰队是1a【k】的矩形,即占据水平的a【k】个长度单位或者竖直a【k】个长度单位,给定的图中“X”处不能放置战舰,

自伤无色的博客 676

Leetcode题解:419. Battleships in a Board

Leetcode题解:419. Battleships in a Board难度:Medium

Littlecuter的博客 493

Leetcode 419. 甲板上的战舰 C++

Leetcode 419. 甲板上的战舰 题目 给定一个二维的甲板, 请计算其中有多少艘战舰。 战舰用 'X’表示,空位用 '.'表示。 你需要遵守以下规则: 给你一个有效的甲板,仅由战舰或者空位组成。 战舰只能水平或者垂直放置。换句话说,战舰只能由 1xN (1 行, N 列)组成,或者 Nx1(N 行, 1 列)组成,其中N可以是任意大小。 两艘战舰之间至少有一个水平或垂直的空位分隔 - 即没有相邻的战舰。 测试样例 示例 : X..X ...X ...X 在上面的甲板中有2艘战舰。 无效样例 :

weixin_43750513的博客 243

LeetCode 419. Battleships in a Board 解题报告

LeetCode 419. Battleships in a Board 解题报告

骆小坑的填坑之旅 5586

【leetcode】419. Battleships in a Board(C++ & Python)

419. Battleships in a Board题目链接419.1 题目描述:Given an 2D board, count how many battleships are in it. The battleships are represented with ‘X’s, empty slots are represented with ‘.’s. You may assume the f

I am what i am 607

2018/12/14周五集训队第九次测试赛补题题解

A - Paper Airplanes CodeForces - 965A (数学) 先算出每个人要用几张纸,然后再算出总共要用几张纸,然后计算用多少包纸 代码 #include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios::sync_with_stdio(0); cin...

weixin_30693183的博客 256
上一篇: LeetCode 343. Integer Break 题解(C++)
下一篇: LeetCode 387. First Unique Character in a String 题解(C++)
prayyojay
博客等级 码龄10年 4粉丝 53原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值