题解——Leetcode 419. Battleships in a Board 难度:Medium
来源:互联网 发布:js字符串截取方法 编辑:程序博客网 时间:2024/06/05 02:41
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) orNx1
(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.
Could you do it in one-pass, using onlyO(1) extra memory andwithout modifying the value of the board?
题目如上,简化后的题意如下:
给你一个方形的板,上面分布着战舰和狭槽,其中战舰用‘X’表示,狭槽用‘.’表示,但战舰的位置有一定限制。战舰可以是一行也可以是一列,而且战舰之间必须隔着狭槽。通过编程算出板上战舰的数量。
除此之外,题目还要求程序只能对板进行一次遍历,使用的额外内存的空间复杂度为O(1),并且不能修改板上战舰和狭槽的分布。
C++程序如下:
class Solution { public: int countBattleships(vector<vector<char>>& board) { int count=0; for(int i = 0; i < board.size(); i++){ for(int j = 0; j < board[0].size(); j++) if(board[i][j]=='X'&&(i==0 || board[i-1][j]!='X')&&(j==0 || board[i][j-1] != 'X')) count++; } return count; } };
战舰的数量等于战舰头的数量,所以当遍历board找到一个'X'时只需要判断它是不是战舰头即可。相对于战舰的非头位置,战舰横向排列时战舰头的左边必定为'.',纵向排列时上边必定为'.'。函数countBattleships()的返回值为战舰的数量,函数参数为数据类型为二维容器的board,由于需要遍历board,所以设置两层嵌套的循环,外层循环次数为board.size()即板的行数,内层循环次数为board[0].size()即板的列数。在循环内判断遍历到的元素是否为战舰头,如果是就将战舰数量加1。
0 0
- 题解——Leetcode 419. Battleships in a Board 难度:Medium
- 题解——Leetcode 419. Battleships in a Board 难度:Medium
- 419. Battleships in a Board 难度:medium
- Leetcode题解:419. Battleships in a Board
- LeetCode 419. Battleships in a Board (Medium)
- 【LeetCode】419.Battleships in a Board(Medium)解题报告
- LeetCode题解:Battleships in a Board
- [Medium]Battleships in a Board
- LeetCode 419. Battleships in a Board 题解(C++)
- Battleships in a Board 题解
- 【leetcode】419. Battleships in a Board【E】
- 419. [LeetCode]Battleships in a Board
- LeetCode 419. Battleships in a Board
- leetcode 419. Battleships in a Board
- LeetCode笔记:419. Battleships in a Board
- LeetCode 419. Battleships in a Board
- [leetcode]419. Battleships in a Board
- 【LeetCode】 419. Battleships in a Board
- Node.js学习笔记(一)基础介绍
- 【头条】JFrog 立足中国快速拓展亚洲业务!通用DevOps解决方案公司宣布进入中国市场!
- hdu 3067 小t的游戏
- usaco2.2 lamps
- Ubuntu16.04下Android studio 模拟器无法启动的解决方法
- 题解——Leetcode 419. Battleships in a Board 难度:Medium
- Ubuntu安装Android-studio
- 针对ie6、7低版本的浏览器时加上标记
- 【J2SE】J2SE小结
- Chronometer 计时器的实现
- cocos2d-js中Hello World代码分析
- 使用专业二进制包仓库Artifactory,实现持续交付
- C# continue 语句的使用
- (转)Android Studio如何安装插件