一次遍历,419. 甲板上的战舰

一、题目

1、题目描述

给你一个大小为 m x n 的矩阵 board 表示甲板,其中,每个单元格可以是一艘战舰 'X' 或者是一个空位 '.' ,返回在甲板 board 上放置的 战舰 的数量。

战舰 只能水平或者垂直放置在 board 上。换句话说,战舰只能按 1 x k1 行,k 列)或 k x 1k 行,1 列)的形状建造,其中 k 可以是任意大小。两艘战舰之间至少有一个水平或垂直的空位分隔 (即没有相邻的战舰)。

2、接口描述

python3
 ​
class Solution:
    def countBattleships(self, board: List[List[str]]) -> int:
cpp
 ​
class Solution {
public:
    int countBattleships(vector<vector<char>>& board) {

    }
};
js
/**
 * @param {character[][]} board
 * @return {number}
 */
var countBattleships = function(board) {

};
 ​php
class Solution {

    /**
     * @param String[][] $board
     * @return Integer
     */
    function countBattleships($board) {

    }
}

3、原题链接

419. 甲板上的战舰


二、解题报告

1、思路分析

即计算连通块个数

网格上如果只是计算连通块个数,我们只需找到多少个方格满足左边和上边都不是'X'

2、复杂度

时间复杂度: O(NM)空间复杂度:O(1)

3、代码详解

python3
 ​
class Solution:
    def countBattleships(self, board: List[List[str]]) -> int:
        cnt = 0
        m, n = len(board), len(board[0])
        for i in range(m):
            for j in range(n):
                if board[i][j] == 'X' and (not i or board[i - 1][j] != 'X') and (not j or board[i][j - 1] != 'X'):
                    cnt += 1
        return cnt
cpp
 ​
class Solution {
public:
    int countBattleships(vector<vector<char>>& board) {
        int m = board.size(), n = board[0].size(), cnt = 0;
        for (int i = 0; i < m; i ++ )
            for (int j = 0; j < n; j ++ )
                if (board[i][j] == 'X' && (!i || board[i - 1][j] != 'X') && (!j || board[i][j - 1] != 'X'))
                    ++ cnt;
        return cnt;
    }
};
js
/**
 * @param {character[][]} board
 * @return {number}
 */
var countBattleships = function(board) {
    let m = board.length, n = board[0].length, cnt = 0;
    for (let i = 0; i < m; i ++ )
        for (let j = 0; j < n; j ++ )
            if (board[i][j] == 'X' && (!i || board[i - 1][j] != 'X') && (!j || board[i][j - 1] != 'X'))
                    ++ cnt;
    return cnt;
};


php
class Solution {

    /**
     * @param String[][] $board
     * @return Integer
     */
    function countBattleships($board) {
        $m = count($board);
        $n = count($board[0]);
        $cnt = 0;
        for ($i = 0; $i < $m; $i ++ )
            for ($j = 0; $j < $n; $j ++ )
                if ($board[$i][$j] == 'X' && (!$i || $board[$i - 1][$j] != 'X') && (!$j || $board[$i][$j - 1] != 'X'))
                    $cnt ++;
        return $cnt;
    }
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EQUINOX1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值