For each X in the board, we just check if the square above it is outside of the grid or is a dot. This works because any X with another X above or to the left of it is a continuation of a previously counted battleship.
class Solution(object): def countBattleships(self, board): total = 0 for i in xrange(len(board)): for j in xrange(len(board)): total += (board[i][j] == "X") and (i == 0 or board[i-1][j] == ".") and (j == 0 or board[i][j-1] == ".") return total