【leetcode】419. Battleships in a Board(C++ & Python)

本文介绍了一种在二维棋盘上计数战舰数量的算法,提供了两种解决方案,并附带了C++及Python代码实现。重点讲解如何通过检查每个单元格来确定战舰头部位置,从而准确计算出战舰总数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


419. Battleships in a Board

题目链接

419.1 题目描述:

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:

1、You receive a valid board, made of only battleships or empty slots.
2、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.
3、At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.

Example:
X..X
…X
…X
In the above board there are 2 battleships.

Invalid Example:
…X
XXXX
…X

This is an invalid board that you will not receive - as battleships will always have a cell separating between them.

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

419.2 解题思路:

  1. 思路一:分为两步:一步用来设置是否访问数组,一步用来遍历输入的二维数组,计算军舰个数。

    • 设置是否访问:遍历计算当前坐标下,为’X’时,遍历与其在同一军舰上的其他’X’处(即同一行或同一列连续为’X’的位置),将其访问值设为已访问1。

    • 计算军舰个数:二重训练遍历二维数组,当其值为’X’且其访问值为未访问0时,军舰计数count++,并且调用访问函数,将目前坐标下与其在同一军舰上的其他’X’坐标的访问值置为1。

  2. 思路二:判断军舰个数,即找到军舰的头即可。头的位置条件是,其左前位置是空的,上的位置是空的即可。判断时,注意棋盘的边界即可,第一行的坐标没有上方位置,第一列的坐标没有左前位置,且(0,0)坐标如果为’X’即为头,其没有左前、上方位置。

419.3 C++代码:

1、思路一代码(9ms):

class Solution139 {
public:
    void ifvisited(vector<vector<char>>& board,vector<vector<int>>& visited, int i, int j)
    {
        int p = i;
        visited[i][j] = 1;
        while (p+1<board.size())
        {
            p++;
            if (board[p][j] == 'X')
                visited[p][j] = 1;
            else                
                break;
        }
        while (j + 1 < board[0].size())
        {
            j++;
            if (board[i][j] == 'X')
                visited[i][j] = 1;
            else
                break;
        }
    }
    int countBattleships(vector<vector<char>>& board) {
        vector<vector<int>> visited(board.size(),vector<int>(board[0].size(),0));
        int count = 0;
        for (int i = 0; i < board.size();i++)
        {
            for (int j = 0; j < board[i].size();j++)
            {
                if (board[i][j] == 'X' && visited[i][j] == 0)
                {
                    count++;
                    ifvisited(board, visited, i, j);
                }
            }
        }
        return count;
    }
};

2、思路二代码(12ms)

class Solution139_1 {
public:
    int countBattleships(vector<vector<char>>& board) {
        int count = 0;
        for (int i = 0; i < board.size(); i++)
        {
            for (int j = 0; j < board[i].size(); j++)
            {
                if (board[i][j] == 'X')
                {
                    if (i == 0 && j == 0)
                        count++;
                    else if (i == 0 && board[i][j - 1] == '.')
                        count++;
                    else if (j == 0 && board[i - 1][j] == '.')
                        count++;
                    else if (j!=0 && i!=0 && board[i-1][j]=='.' && board[i][j-1]=='.')
                        count++;
                    else continue;
                }
            }
        }
        return count;
    }
};

2、思路二代码(6ms)

class Solution139_2 {
public:
    int countBattleships(vector<vector<char>>& board) {
        int count = 0;
        for (int i = 0; i < board.size(); i++)
        {
            for (int j = 0; j < board[i].size(); j++)
            {
                if (board[i][j] == 'X' &&  (i==0 || board[i-1][j]=='.') && (j==0 || board[i][j-1]=='.') )
                    count++;
            }
        }
        return count;
    }
};

419.4 Python代码:

1、思路一代码(76ms)

class Solution(object):
    def countBattleships(self, board):
        """
        :type board: List[List[str]]
        :rtype: int
        """
        def ifvisited(board,visited,i,j):
            visited[i][j]=1
            p=i
            while p+1<len(board):
                p+=1
                if board[p][j]=='X':
                    visited[p][j]=1
                else:
                    break
            while j+1<len(board[0]):
                j+=1
                if board[i][j]=='X':
                    visited[i][j]=1
                else:
                    break                   
        visited=[[0 for i in range(len(board[0]))] for j in range(len(board))]
        count=0
        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j]=='X' and visited[i][j]==0:
                    count+=1
                    ifvisited(board, visited, i, j)
        return count

2、思路二代码(52ms)

class Solution1(object):
    def countBattleships(self, board):
        """
        :type board: List[List[str]]
        :rtype: int
        """
        count=0
        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j]=='X' and (i==0 or board[i-1][j]=='.') and (j==0 or board[i][j-1]=='.'):
                    count+=1
        return count

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值