Python solution


  • 14
    class Solution(object):
        def countBattleships(self, board):
            if len(board) == 0: return 0
            m, n = len(board), len(board[0])
            count = 0
            for i in range(m):
                for j in range(n):
                    if board[i][j] == 'X' and (i == 0 or board[i-1][j] == '.') and (j == 0 or board[i][j-1] == '.'):
                        count += 1
            return count
    

  • -1

    @simkieu I understand your solution,but do you know why it takes 46ms to run this code?The best solution given by java takes less than 1ms, do you know the reason?


  • 0

    @skywalker_tju : I think because Python is much slower than Java. You can try to replace 'range' with 'xrange' and see if it helps.


  • 1
    W

    @skywalker_tju Well, as a script-based language, Python is expected to run much lower than other advanced language; However, in practice, you can use Cython or Psyco to convert your Python code to C or other machine language to boost the performance.


  • 2
    L

    How do you handle the invalid cases of battleships display?


  • 0
    M

    @LeoZhu I don't think the code needs to handle it. It's ruled out.


  • 2
    M

    A similar but maybe cleaner solution.

    def countBattleships(self, board):
        total = 0
        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j] == 'X':
                    flag = 1
                    if j > 0 and board[i][j-1] == 'X': flag = 0
                    if i > 0 and board[i-1][j] == 'X': flag = 0
                    total += flag
        return total

  • 0

    @LeoZhu In the description, it says you will not receive an invalid board.


Log in to reply
 

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