LeetCode 419. Battleships in a Board (Medium)
来源:互联网 发布:阿里云服务器学生1元 编辑:程序博客网 时间:2024/06/08 19:29
题目描述:
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.
题目大意:给出一个图,竖着的X的组合或者横着的X的组合为一条船,船与船之间有空位(’.’),求船的数量。
思路:观察图可以发现,只要是一艘船,它的头的左边或者上边是不会有X的(因为它是头,如果左边有X说明它是横的船身,上边有X说明它是竖的船身)。那么只用遍历图,算出船头数量即可。
c++代码:
class Solution {public: int countBattleships(vector<vector<char>>& board) { int ans = 0; for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[i].size(); j++) { if (board[i][j] == 'X') { if (i == 0) { if (j == 0) ans++; else { if (board[i][j - 1] != 'X') ans++; } } else { if (j == 0) { if (board[i - 1][j] != 'X') ans++; } else { if (board[i - 1][j] != 'X' && board[i][j - 1] != 'X') ans++; } } } } } return ans; }};
- LeetCode 419. Battleships in a Board (Medium)
- 【LeetCode】419.Battleships in a Board(Medium)解题报告
- 419. Battleships in a Board 难度:medium
- [Medium]Battleships in a Board
- 【leetcode】419. Battleships in a Board【E】
- Leetcode题解:419. 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
- 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
- Leetcode-419. Battleships in a Board
- 【LeetCode】419. Battleships in a Board
- Kruscal算法的C++实现
- Python操作Kafka
- 欢迎使用CSDN-markdown编辑器
- LayoutInflater源码分析
- TabLayout && ViewPager _MyActivity(主页)
- LeetCode 419. Battleships in a Board (Medium)
- 日常训练—cf 2017 USP Try-out
- 渗透测试:密码破解小结
- 数据库的一个表一直在使用中 没法查询
- 8. String to Integer (atoi)
- bnuoj 34985 Elegant String dp+矩阵快速幂
- Nginx 图片防盗链 正确配置 已测试通过
- WPF学习散记——生成固定大小界面框
- TabLayout && ViewPager _动态添加Fragnent