Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules:

You receive a valid board, made of only battleships or empty slots.
Battleships can only be placed horizontally or vertically. In other words,
they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size. At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.

DFS

Time Complexity:
O(row*col)
Space Complexity:
O(max(row, col))

思路

Use tradition dfs for 4 directions which can consist of ships. Make the visited board of matrix "#" so we won't visit it again.

代码

public int countBattleships(char[][] board) {
    if(board == null || board.length == 0 || board[0] == null || board[0].length == 0) return 0;
    int rows = board.length, cols = board[0].length;
    int count = 0;
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
            if(board[i][j] == 'X'){
                helper(board, i, j, rows, cols);
                count++;
            }
        }
    }
    return count;
}

private void helper(char[][] board, int i, int j, int rows, int cols){
    if(i < 0 || i >= rows || j < 0 || j >= cols || board[i][j] != 'X') return;
    board[i][j] = '#';
    helper(board, i - 1, j, rows, cols);
    helper(board, i, j - 1, rows, cols);
    helper(board, i, j + 1, rows, cols);
    helper(board, i + 1, j, rows, cols);
}

优化

Time Complexity: O(row * col)
Space Complexity: O(1)

思路

Because the board is always valid which means at least one horizontal or vertical cell separates between two battleships. We can check for the first cells by only counting cells that do not have an 'X' to the left and do not have an 'X' above them.

代码

public int countBattleships(char[][] board) {
    if(board == null || board.length == 0 || board[0] == null || board[0].length == 0) return 0;
    int rows = board.length, cols = board[0].length, count = 0;
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
            if(board[i][j] == '.') continue;
            if(i > 0 && board[i - 1][j] == 'X') continue;
            if(j > 0 && board[i][j - 1] == 'X') continue;
            count++;
        }
    }
    return count;
}

annielulu
5 声望5 粉丝