LeetCode[419] Battleships in a Board
来源:互联网 发布:海鸥手表怎么样 知乎 编辑:程序博客网 时间:2024/06/01 09:38
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 not a valid board - as battleships will always have a cell separating between them.
Your algorithm should not modify the value of the board.
遍历各点,遇到 'X' 就把cnt + 1,并且把经过的 ‘X’ 都变为 '.'
class Solution {public:int countBattleships(vector<vector<char>>& board) {vector<vector<char>> tmp = board;int n1 = board.size(), n2 = board[0].size();int cnt = 0;for (int i = 0; i < n1; ++i) {for (int j = 0; j < n2; ++j) {if (tmp[i][j] == 'X') {tmp[i][j] = '.';++cnt;int a = i, b = j;while (a + 1 < n1 && tmp[a + 1][b] == 'X') {++a;tmp[a][b] = '.';}while (b + 1 < n2 && tmp[a][b + 1] == 'X') {++b;tmp[a][b] = '.';}}}}return cnt;}};
0 0
- LeetCode[419] Battleships in a Board
- LeetCode #419: Battleships in a Board
- leetcode 419 Battleships in a Board C++
- 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 Battleships in a Board
- Battleships in a Board [Leetcode]
- LeetCode-Battleships in a Board
- LeetCode 419 Battleships in a Board (DFS 或 模拟)
- 【leetcode】419. Battleships in a Board【E】
- Leetcode题解:419. Battleships in a Board
- leetcode oj java Battleships in a Board
- 419. [LeetCode]Battleships in a Board
- LeetCode 419. Battleships in a Board
- leetcode 419. Battleships in a Board
- LeetCode笔记:419. Battleships in a Board
- 简简单单的爬虫
- 346_桌面悬浮窗
- HTML-列表
- 2016微信营销的几点思考:流量与渠道
- android 开发 app全局字体的设置
- LeetCode[419] Battleships in a Board
- Flask项目的代码组织方式
- 批处理实现以字符串/关键字删选文档内容
- SpringInAction学习笔记:运行时值注入
- 计算机进制和计算
- python之sys模块详解
- Easy 155题 Min Stack
- 简单DFS 哈密顿绕行世界问题
- Android TV开发总结(四)通过RecycleView构建一个TV app列表页(仿腾讯视频TV版)