JZX轻语:简

LeetCode 419 - 甲板上的战舰

发表于2024年06月11日

#枚举

本来想通过DFS这些方法来扫描的,后面发现只要枚举每个战舰的起点即可:只要某个’X’的左边和上边都不是’X’,那么这个’X’就是一个战舰的起点。

class Solution:
    def countBattleships(self, board: List[List[str]]) -> int:
        ans = 0

        for i in range(len(board)):
            for j in range(len(board[i])):
                if board[i][j] == 'X' and (i == 0 or board[i - 1][j] == '.') and (j == 0 or board[i][j - 1] == '.'):
                    ans += 1
        return ans

闪念标签:LC

题目链接:https://leetcode.cn/problems/battleships-in-a-board/