Battleships in a Board(计算甲板上的军舰数)

首先想到的是DFS方法,如下

class Solution(object):
    def countBattleships(self, board):
        """
        :type board: List[List[str]]
        :rtype: int
        """
        vs = []
        h = len(board)
        v = len(board[0])
        ans = 0
        if h is None: 
            return 0
    
        def dfs(x,y):
            for dx,dy in zip((1,0,-1,0),(0,1,0,-1)):
                nx = x+dx
                ny = y+dy
                if 0<=nx<h and 0<=ny<v:
                    if (nx, ny) not in vs and board[nx][ny] == 'X':
                        vs.append((nx,ny))
                        dfs(nx,ny)
        
    
        for i in range(0,h):
            for j in range(0,v):
                if (i,j) not in vs and board[i][j] == 'X':
                    ans += 1
                    vs.append((i,j))
                    dfs(i,j)
        return ans

然而,超时了。想了想,有些地方重复了两次,完全没必要,我们只要保证X的左边和上面没有X就OK,
所以换成下面的:

class Solution(object):
    def countBattleships(self, board):
        """
        :type board: List[List[str]]
        :rtype: int
        """
        v = len(board)
        h = len(board[0])
        ans = 0
        if v is None: 
            return 0
        for i in range(0,v):
            for j in range(0,h):
                if i == 0 and j == 0 and board[i][j] == 'X': 
                    ans += 1
                if i == 0 and j>=1:
                    if board[0][j] == 'X' and board[0][j-1] == '.':
                        ans += 1
                if j == 0 and i>=1:
                    if board[i][0] == 'X' and board[i-1][0] == '.':
                        ans += 1
                if i >=1 and j >=1:
                    if board[i][j] == 'X' and board[i-1][j] == '.' and board[i][j-1] =='.':
                        ans +=1
                        
        return ans

AC
主要学习了一下深度优先搜索,这个好久没看过了,有些细节记不太清了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,351评论 0 33
  • The Last Question 最后的问题 By Isaac Asimov 阿西莫夫 This is by f...
    beyond_cosmos阅读 4,385评论 0 8
  • 作者:阿西莫夫(Isaac Asimov) 译者:青铮 这是我所有的故事中最钟爱的一篇。 我试图把人类亿万年的历程...
    QishengPan阅读 4,605评论 1 10
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,633评论 25 709
  • 通讯 QQ微信微博贴吧豆瓣天涯 购物 支付宝淘宝美团百度糯米京东 出行 百度地图优步滴滴 生活 百度输入法建设银行...
    静候那一米阳光阅读 1,371评论 0 2