1-liner in Python


  • 0
    O
    class Solution(object):
        def countBattleships(self, board):
            return sum(c=='X' and (j==0 or board[i][j-1]=='.') and (i==0 or board[i-1][j]=='.') for i,row in enumerate(board) for j,c in enumerate(row))
    

    which came from this:

    class Solution(object):
        def countBattleships(self, board):
            n = len(board)
            if n == 0:
                return 0
            m = len(board[0])
            ret = 0
            for i in range(n):
                for j in range(m):
                    cell = board[i][j]
                    left = board[i][j-1] if j-1>=0 else '.'
                    up = board[i-1][j] if i-1>=0 else '.'
                    if cell == 'X' and left == up == '.':
                        ret += 1
            return ret
    

Log in to reply
 

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