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