-
发表于 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 题目链接
-