leetcode
来源:互联网 发布:网站的数据库是什么 编辑:程序博客网 时间:2024/06/11 22:36
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.
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.
Follow up:
Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?
mysolution:
大致思路:
题目大概意思是 隔列或者隔行排战舰,求这些战舰总数量。所以我们能准确找到每行或每列第一艘战舰即可。
class Solution {public: int countBattleships(vector<vector<char>>& board) { int num = 0; if(board.size()==0) return num; int i = board.size(); int j = board[0].size(); for (int m = 0; m < i; ++ m) { for (int n = 0; n < j; ++n) { if(board[m][n] == '.') continue; if(m > 0 && board[m -1][n] == 'X') continue; if(n > 0 && board[m][n-1] == 'X') continue; ++num; } } return num; }};
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- http请求的步骤
- 《数学之美》总结(第1章~第3章)
- LeetCode 461. Hamming Distance
- C语言strtok()函数:字符串分割
- 学习记录
- leetcode
- html5 图片上传,支持图片预览、压缩、及进度显示,兼容IE6+及标准浏览器
- ViewGroup事件分发机制(源码)
- Android MediaPlayer(多媒体播放)
- 备忘录模式
- ACMzipper
- 学习TimePicker和DataPicker
- 粗谈计算机组成
- 自定义索引View