Leetcode 419. Battleships in a Board解题报告(python)

本文介绍了一种在二维棋盘上计数战舰数量的Python算法。战舰仅能水平或垂直放置,且彼此间至少有一个空格相隔。算法通过检查每个'X'字符的上下左右位置来确定独立战舰的数量。

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

419. Battleships in a Board

  1. Battleships in a Board python solution

题目描述

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.

在这里插入图片描述

解析

本题的意思是求解board上一共有多少个战舰。战舰本身的限制是只能垂直或者水平摆放,相邻战舰会有’.'将其隔开。所以解题思路也比较简单,当检测到‘X’时,判断下它的左边和上边是否也是‘X’,如果是那么同一艘战舰。如果不是就是不同的战舰,计数加一。

// An highlighted block
class Solution:
    def countBattleships(self, board: List[List[str]]) -> int:
        count=0
        for row in range(len(board)):
            for col in range(len(board[0])):
                if board[row][col]=='X':
                    if row>0 and board[row-1][col]=='X' or col>0 and board[row][col-1]=='X':
                        continue
                    count+=1
        return count     

Reference

https://leetcode.com/problems/battleships-in-a-board/discuss/180429/Python-solution

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值