419. Battleships in a Board 难度:medium
来源:互联网 发布:js获取浏览器高度 编辑:程序博客网 时间:2024/06/04 21:16
题目:
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) 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.
Example:
X..X...X...XIn the above board there are 2 battleships.
Invalid Example:
...XXXXX...XThis is an invalid board that you will not receive - as battleships will always have a cell separating between them.
思路:
从左向右,从上向下遍历board,只需要判断当前所在位置是否为X
以及是否能使得battership的数量增加
程序:
class Solution {public: int countBattleships(vector<vector<char>>& board) { int count = 0; int m = board.size(); int n = board[0].size(); for(int i = 0;i < m;i++) { for(int j = 0;j < n;j++) { if(board[i][j] == 'X') { count += 1; for(int p = j + 1;p < n;p++) { if(board[i][p] == '.') break; board[i][p] = '.'; } for(int p = i + 1;p < m;p++) { if(board[p][j] == '.') break; board[p][j] = '.'; } board[i][j] = '.'; } } } return count; }};
0 0
- 419. Battleships in a Board 难度:medium
- [Medium]Battleships in a Board
- 题解——Leetcode 419. Battleships in a Board 难度:Medium
- 题解——Leetcode 419. Battleships in a Board 难度:Medium
- LeetCode 419. Battleships in a Board (Medium)
- 【LeetCode】419.Battleships in a Board(Medium)解题报告
- 419. Battleships in a Board
- 419. Battleships in a Board
- 419. Battleships in a Board
- 419. Battleships in a Board
- 419. Battleships in a Board
- 419. Battleships in a Board
- 419. Battleships in a Board
- 419. Battleships in a Board
- 419. Battleships in a Board
- 419. Battleships in a Board
- 419. Battleships in a Board
- 419. Battleships in a Board
- 深入了解JAVA可变长度的参数(Varargs)
- support-percent
- 微信小程序checkbox排列方向
- 4.面向对象
- 【9-1-7】链表的冒泡 bubblesort
- 419. Battleships in a Board 难度:medium
- ES6的变量声明
- 66. Plus One
- 2017年了,别再混日子了
- openjdk8的安装
- linux环境下找出今天被修改的文件
- Hadoop Yarn 框架原理及运作机制
- CentOS6.5_64位系统下安装配置postfix邮件系统 启用并配置SMTP在第三方上边使用发送邮件
- 3.9触摸事件分发的例子-选择英雄图标,切换对应英雄,控制其移动。