Python Solution


  • 0
    T
    def countBattleships(self, board):
            """
            :type board: List[List[str]]
            :rtype: int
            """
            # check validity of the board
            if board is None:
                return 0
    
            num_row = len(board)
            num_col = len(board[0])
    
            # check num_row, num_col
            if num_row == 0 or num_col == 0:
                return 0
    
            # check how many boats in the board
            # the boats should meet the requirement
            # 1. itself is *
            # 2. either right is */down is *
            # 3. left is . and up is .
            count_total = 0
    
            for i in range(num_row):
                for j in range(num_col):
                    if board[i][j] == 'X':
                        # vertical boat
                        if (j==0 or board[i][j-1]=='.') and (i==0 or board[i-1][j]=='.'):
                            count_total+=1
    
            # last column
            return count_total
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.