Leetcode 419.甲板上的战舰

原题链接:Leetcode 419. Battleships in a Board

Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board.

Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).

Example 1:
在这里插入图片描述

Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]
Output: 2

Example 2:

Input: board = [["."]]
Output: 0

Constraints:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 200
  • board[i][j] is either '.' or 'X'.

Follow up: Could you do it in one-pass, using only O(1) extra memory and without modifying the values board?


题目大意:

有一个m x n 的矩阵代表着甲板,甲板中有着若干的战舰。
战舰只能水平或者竖直放置。
一艘战舰在矩阵中用长度为1,宽度为k的字符 'X'组成的块来表示。战舰之间不彼此相连,问你甲板中战舰的数量。

方法二:枚举起点

思路:

由于战舰总是水平或竖直放置,我们可以认定水平战舰的最左端和竖直战舰的最上端为战舰的起点。
遍历一遍二维数组,只需要统计起点的个数就能得道战舰的数量。
这也正是补充中提到的不改变矩阵的方法。

C++ 代码:

class Solution {
public:
    int countBattleships(vector<vector<char>>& board) {
        
        // 加班的行数和列数
        int row = board.size();
        int col = board[0].size();
        int ans = 0;

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

复杂度分析:

  • 时间复杂度:O(mn),遍历了一遍二维数组
  • 空间复杂度:O(1)

相关推荐

  1. 419.甲板战舰

    2024-04-07 08:58:01       5 阅读
  2. Leetcode459:重复字符串

    2024-04-07 08:58:01       43 阅读
  3. Leetcode 414.第三大

    2024-04-07 08:58:01       40 阅读
  4. Leetcode 459:重复子字符串

    2024-04-07 08:58:01       18 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-07 08:58:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-07 08:58:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-07 08:58:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-07 08:58:01       20 阅读

热门阅读

  1. Marketo营销自动化集成Zoho CRM

    2024-04-07 08:58:01       15 阅读
  2. 即将上-UE独立程序高级开发-自动化系统

    2024-04-07 08:58:01       19 阅读
  3. notepad++绿色版添加右键菜单

    2024-04-07 08:58:01       19 阅读
  4. leetcode148. 排序链表

    2024-04-07 08:58:01       17 阅读
  5. TypeScript快速入门

    2024-04-07 08:58:01       14 阅读
  6. c++中c风格的字符串

    2024-04-07 08:58:01       22 阅读