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

被折叠的 条评论
为什么被折叠?



