class Solution(object): def countBattleships(self, board): if len(board) == 0: return 0 m, n = len(board), len(board) 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
@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?
@skywalker_tju : I think because Python is much slower than Java. You can try to replace 'range' with 'xrange' and see if it helps.
@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.
@LeoZhu I don't think the code needs to handle it. It's ruled out.
A similar but maybe cleaner solution.
def countBattleships(self, board): total = 0 for i in range(len(board)): for j in range(len(board)): 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
@LeoZhu In the description, it says you will not receive an invalid board.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.