[LeetCode] 419. Battleships in a Board

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值