Skip to content

419. Battleships in a Board

  • Time: $O(mn)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int countBattleships(vector<vector<char>>& board) {
    int ans = 0;

    for (int i = 0; i < board.size(); ++i)
      for (int j = 0; j < board[0].size(); ++j) {
        if (board[i][j] == '.')
          continue;
        if (i > 0 && board[i - 1][j] == 'X')
          continue;
        if (j > 0 && board[i][j - 1] == 'X')
          continue;
        ++ans;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int countBattleships(char[][] board) {
    int ans = 0;

    for (int i = 0; i < board.length; ++i)
      for (int j = 0; j < board[0].length; ++j) {
        if (board[i][j] == '.')
          continue;
        if (i > 0 && board[i - 1][j] == 'X')
          continue;
        if (j > 0 && board[i][j - 1] == 'X')
          continue;
        ++ans;
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def countBattleships(self, board: list[list[str]]) -> int:
    ans = 0

    for i, row in enumerate(board):
      for j, cell in enumerate(row):
        if cell == '.':
          continue
        if i > 0 and board[i - 1][j] == 'X':
          continue
        if j > 0 and board[i][j - 1] == 'X':
          continue
        ans += 1

    return ans