Python clean solution beats 97%


  • 0
    J

    
    def countBattleships(self, board):
            """
            :type board: List[List[str]]
            :rtype: int
            """
            result = 0
            for i in range(len(board)):
                for j in range(len(board[0])):
                    if board[i][j] == "X":
                        ver_pre = False 
                        if i == 0 or (i>0 and board[i-1][j] == "."):
                            ver_pre = True
                        hor_pre = False
                        if j == 0 or (j>0 and board[i][j-1] == "."):
                            hor_pre = True
                        if hor_pre and ver_pre: #Add a battleship only when there is no battleship before it both horizontally and veirtically
                            result += 1
            return result
    

Log in to reply
 

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