419. Battleships in a Board 线性时间原地解法 Python版本

419. Battleships in a Board

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.

419. 甲板上的战舰

 

给定一个二维的甲板, 请计算其中有多少艘战舰。 战舰用 'X'表示,空位用 '.'表示。 你需要遵守以下规则:

  • 给你一个有效的甲板,仅由战舰或者空位组成。
  • 战舰只能水平或者垂直放置。换句话说,战舰只能由 1xN (1 行, N 列)组成,或者 Nx1 (N 行, 1 列)组成,其中N可以是任意大小。
  • 两艘战舰之间至少有一个水平或垂直的空位分隔 - 即没有相邻的战舰。

 


分析:

我按行优先和列优先把每个战舰都算两遍,最后除以2即可。但对于长条形的战舰,如横向长条,则首次搜索到+1,连续搜索-1,以抵消纵向遍历时算多的次数。

代码如下:(关于二维面积的线性时间,原地空间)

class Solution:
    def countBattleships(self, board: List[List[str]]) -> int:
        ans=0
        row,col=len(board),len(board[0])
        for i in range(row):
            for j in range(col):
                if 'X'==board[i][j]:
                    ans += 1 if 0==j or '.'==board[i][j-1] else -1
        for i in range(col):        #交换行列次序
            for j in range(row):
                if 'X'==board[j][i]:#交换行列次序
                    ans += 1 if 0==j or '.'==board[j-1][i] else -1
        return ans//2

两组双层的for循环仅仅是改变行列循环次序。所以是复制粘贴稍微改下就能解决的事情。

 

还有一种解法也是同样复杂度的,仅当该节点是'X'且其左边和上边不是'X'或越界则ans++,即只算每搜战舰的左上角,其实这种解法更容易理解,只是我一开始就想成这样了。

解释可能不是很完善,以后再写,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值