419. Battleships in a Board
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.
419. 甲板上的战舰
给定一个二维的甲板, 请计算其中有多少艘战舰。 战舰用 'X'
表示,空位用 '.'
表示。 你需要遵守以下规则:
- 给你一个有效的甲板,仅由战舰或者空位组成。
- 战舰只能水平或者垂直放置。换句话说,战舰只能由
1xN
(1 行, N 列)组成,或者Nx1
(N 行, 1 列)组成,其中N可以是任意大小。 - 两艘战舰之间至少有一个水平或垂直的空位分隔 - 即没有相邻的战舰。
分析:
我按行优先和列优先把每个战舰都算两遍,最后除以2即可。但对于长条形的战舰,如横向长条,则首次搜索到+1,连续搜索-1,以抵消纵向遍历时算多的次数。
代码如下:(关于二维面积的线性时间,原地空间)
class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
ans=0
row,col=len(board),len(board[0])
for i in range(row):
for j in range(col):
if 'X'==board[i][j]:
ans += 1 if 0==j or '.'==board[i][j-1] else -1
for i in range(col): #交换行列次序
for j in range(row):
if 'X'==board[j][i]:#交换行列次序
ans += 1 if 0==j or '.'==board[j-1][i] else -1
return ans//2
两组双层的for循环仅仅是改变行列循环次序。所以是复制粘贴稍微改下就能解决的事情。
还有一种解法也是同样复杂度的,仅当该节点是'X'且其左边和上边不是'X'或越界则ans++,即只算每搜战舰的左上角,其实这种解法更容易理解,只是我一开始就想成这样了。
解释可能不是很完善,以后再写,