解题思路
可以通过战舰的头来判断个数,当一个点上面或者左面试X说明它战舰中间部分.
将模型分为三个部分分析即可。
网络异常,图片无法展示
|
代码
class Solution(object): def countBattleships(self, board): """ :type board: List[List[str]] :rtype: int """ count = 0 for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == "X": count += 1 if i == 0 and j > 0: if board[i][j-1] == "X": count = count - 1 elif j == 0 and i > 0: if board[i-1][j] == "X": count = count - 1 elif i > 0 or j > 0: if board[i][j-1] == "X" or board[i-1][j] == "X": count = count - 1 return count