基本思路:只需要找船头,对行列所有都遍历,遇到"."则跳过,遇到'x'则测试他上面或者左边是否有‘x’,没有则证明他是船头,答案加1,代码如下:
class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
m,n=len(board),len(board[0])
ans=0
for i in range (m):
for j in range (n):
if board[i][j]==".": continue
if j>0 and board[i][j-1]=='X':continue
if i>0 and board[i-1][j]=="X":continue
ans+=1
return ans