1. 程式人生 > >python leetcode 419. Battleships in a Board

python leetcode 419. Battleships in a Board

無難度 按照題意解題即可
按照遍歷順序只需判斷左邊和上邊是否相連

class Solution:
    def countBattleships(self, board):
        """
        :type board: List[List[str]]
        :rtype: int
        """
        m=len(board)
        if m==0: return 0
        n=len(board[0])
        count=0
        for i in range(m):
            for j in range(n):
                if board[i][j]=='X':
                    if (i-1<0 or board[i-1][j]=='.') and (j-1<0 or board[i][j-1]=='.'):
                        count+=1
        return count