- 921. Minimum Add to Make Parentheses Valid 使括号有效的最少添加
- 915. Partition Array into Disjoint Intervals 分割数组
- 932. Beautiful Array 漂亮数组
- 940. Distinct Subsequences II 不同的子序列 II
题目地址:https://leetcode.com/problems/battleships-in-a-board/description/
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:
...X
XXXX
...X
This is an invalid board that you will not receive - as battleships will always have a cell separating between them.
Follow up:
战列舰计数。第一遍看这个题的时候看不懂,看了别人的解答,我算是明白了,就是求用x组成的区域有几个。单独的一个或者连续的一条线都算一个。另外就是战列舰不会交叉,不会平行。
方法比较简单,直接数就行。如果一个位置有x,并且(这个位置在最左边或者不在最左边但是该位置左侧是.),并且(这个位置在最上边或者不在最上边但是该位置上侧是.),那么就是一个新的战列舰,计数即可。
class Solution(object):
def countBattleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
if len(board) == 0 or len(board[0]) == 0:
return 0
row, col = len(board), len(board[0])
count = 0
for i in xrange(row):
for j in xrange(col):
if board[i][j] == 'X' and (i == 0 or board[i - 1][j] == '.') and (j == 0 or board[i][j - 1] == '.'):
count += 1
return count
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
C++版本代码如下
class Solution {
public:
int countBattleships(vector<vector<char>>& board) {
int M = board.size();
int N = board[0].size();
int res = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (board[i][j] == 'X' && (i == 0 || board[i - 1][j] == '.') && (j == 0 || board[i][j - 1] == '.'))
res ++;
}
}
return res;
}
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
DDKK.COM 弟弟快看-教程,程序员编程资料站,版权归原作者所有
本文经作者:负雪明烛 授权发布,任何组织或个人未经作者授权不得转发
所以,我必须在 10x10 的板上制作一个用户对计算机的 Battleship 游戏来上编程课。我必须让计算机随机放置五艘大小为 5、4、3、3 和 2 的船。 我所做的是,我生成了 0 到 9 之间
我正在学习创建一个java游戏,对java来说还是个新手。现在我想创建一个战舰游戏。但现在我被困在这里了。现在,当我随机放置船作为电脑板时,有时它会与之前的船重叠,因此游戏变得不平衡。其次,在我收到玩
我正在制作战舰游戏,一切正常。但是由于我加入了一个回合系统,游戏无法正常运行。游戏有两个棋盘(一个是隐藏的,另一个是“公开的”,对手可以看到(所以没有船只)。隐藏的有效,但公众每回合都会重置,所以你看
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎是题外话,因为它缺乏足够的信息来诊断问题。 更详细地描述您的问题或include a min
这个问题不太可能帮助任何 future 的访问者;它只与一个小的地理区域、一个特定的时间点或一个非常狭窄的情况有关,这些情况并不普遍适用于互联网的全局受众。为了帮助使这个问题更广泛地适用,visit
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 9 年前。 Improve th
我正在制作一款战舰游戏。我创建了一个 Ship 类来为船只提供位置。 创建类后,我必须创建所有实例,我想知道是否有一种方法可以自动化它。 大部分程序都是无关紧要的,但我将其保留,以防万一它可能会影响它
我的编译器告诉我有错误,但我已经给我的导师发了电子邮件,他说我的代码非常好。 错误是错误: 1 error C4716: 'ShipPlacement' : must return a value,
我是一个想学习Java的菜鸟。我正在阅读《Head First Java》一书,并且非常喜欢它。我在学习使用 ArrayList<> 时遇到了一个问题而不是常规的array[] 。我在尝试分配 int
我是一名优秀的程序员,十分优秀!