博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
419. Battleships in a Board
阅读量:6469 次
发布时间:2019-06-23

本文共 1824 字,大约阅读时间需要 6 分钟。

题目描述:

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 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:

...XXXXX...X

This is an invalid board that you will not receive - as battleships will always have a cell separating between them.

 

Follow up:

Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?

解题思路:

善于利用题目信息”This is an invalid board that you will not receive - as battleships will always have a cell separating between them.“,battleship不相邻,一个点如果是battleship中一点,当battleship的长度大于一时其横向或者纵向临近的点肯定是'X',当battleship的长度为一时其临近的点都是‘.’。因此,对于每个battleship,我们只统计其纵向或者横向的第一个点。

代码:

1 class Solution { 2 public: 3     int countBattleships(vector
>& board) { 4 int num = 0; 5 int col = board[0].size(); 6 int row = board.size(); 7 for (int i = 0; i < row; ++i) { 8 for (int j = 0; j < col; ++j) { 9 if (board[i][j] == 'X') {10 if (i > 0 && board[i-1][j] == 'X')11 continue;12 if (j > 0 && board[i][j-1] == 'X')13 continue;14 num++;15 }16 }17 }18 return num;19 }20 };

 

转载于:https://www.cnblogs.com/gsz-/p/9439691.html

你可能感兴趣的文章
[转]Windows的批处理脚本
查看>>
lnmp高人笔记
查看>>
子程序框架
查看>>
多维数组元素的地址
查看>>
数据库运维体系_SZMSD
查看>>
福大软工1816 · 第三次作业 - 结对项目1
查看>>
selenium多个窗口切换
查看>>
静态库 调试版本 和发布版本
查看>>
JAVA中的finalize()方法
查看>>
慕课网学习手记--炫丽的倒计时效果Canvas绘图与动画基础
查看>>
==与equals()的区别
查看>>
基本分类方法——KNN(K近邻)算法
查看>>
在XenCenter6.2中构建CentOS7虚拟机的启动错误
查看>>
.NET Framework3.0/3.5/4.0/4.5新增功能摘要
查看>>
php中表单提交复选框与下拉列表项
查看>>
熟悉常用的Linux操作
查看>>
面象过程与面象对象
查看>>
谷歌设置支持webgl
查看>>
js的AJAX请求有关知识总结
查看>>
Eclipse添加新server时无法选择Tomcat7的问题
查看>>