Python 1-liner


  • 2
    def countBattleships(self, b):
        return sum(all([b[y][x]=='X',x<1 or b[y][x-1]!='X',y<1 or b[y-1][x]!='X']) for y in range(len(b)) for x in range(len(b[0])))
    

    Same concept in a few more lines for better readability. Count the top&left corner of each ship:

    def countBattleships(self, board):
        res = 0
        for y in range(len(board)):
            for x in range(len(board[0])):
                if all([board[y][x] == 'X',
                        not x or board[y][x-1] != 'X',
                        not y or board[y-1][x] != 'X']):
                    res += 1
        return res

  • 3

    Looks like you were golfing a bit :-). Here are some step-by-step improvements and at the end my own solution (that I wrote after seeing @ben65's solution):

    def countBattleships(self, b):
       #return sum(all([b[y][x]=='X',x<1 or b[y][x-1]!='X',y<1 or b[y-1][x]!='X']) for y in range(len(b)) for x in range(len(b[0])))
       #return sum(all([b[y][x]=='X',x<1or b[y][x-1]!='X',y<1or b[y-1][x]!='X'])for y in range(len(b))for x in range(len(b[0])))
       #return sum(all([b[y][x]>'.',x<1or b[y][x-1]<'X',y<1or b[y-1][x]<'X'])for y in range(len(b))for x in range(len(b[0])))
       #return sum(all([b[y][x]>'.',x<1or'X'>b[y][x-1],y<1or'X'>b[y-1][x]])for y in range(len(b))for x in range(len(b[0])))
       #return sum(all([c>'.',x<1or'X'>r[x-1],y<1or'X'>b[y-1][x]])for y,r in enumerate(b)for x,c in enumerate(r))
        return sum(zip(r,['.']+r,p or'.'*len(r)).count(tuple('X..'))for r,p in zip(b,[0]+b))
    

Log in to reply
 

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