zoukankan      html  css  js  c++  java
  • leetcode_419. 甲板上的战舰

    给定一个二维的甲板, 请计算其中有多少艘战舰。 战舰用 'X'表示,空位用 '.'表示。 你需要遵守以下规则:
    
    给你一个有效的甲板,仅由战舰或者空位组成。
    战舰只能水平或者垂直放置。换句话说,战舰只能由 1xN (1 行, N 列)组成,或者 Nx1 (N 行, 1 列)组成,其中N可以是任意大小。
    两艘战舰之间至少有一个水平或垂直的空位分隔 - 即没有相邻的战舰。
    示例 :
    
    X..X
    ...X
    ...X
    在上面的甲板中有2艘战舰。
    
    无效样例 :
    
    ...X
    XXXX
    ...X
    你不会收到这样的无效甲板 - 因为战舰之间至少会有一个空位将它们分开。
    
    进阶:
    
    你可以用一次扫描算法,只使用O(1)额外空间,并且不修改甲板的值来解决这个问题吗?
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/battleships-in-a-board
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    
    class Solution:
        def countBattleships(self, board: List[List[str]]) -> int:
            #x只是战舰的一部分,战舰只能水平或者垂直放置,所以战舰头的左边和上边一定不是 X
            a=len(board)#行
            b=len(board[0])#列
            res=0
            for i in range(a):
                for j in range(b):
                    if board[i][j]=='X' and (i==0 or board[i-1][j]=='.') and (j==0 or board[i][j-1]=='.'):
                        res+=1
            return res
    
    #DFS
    class Solution:
        def countBattleships(self, board: List[List[str]]) -> int:
            def dfs(board,r,c):
                board[r][c]=0
                nr=len(board)
                nc=len(board[0])
                for x,y in [(r-1,c),(r+1,c),(r,c-1),(r,c+1)]:
                    if 0<=x<nr and 0<=y<nc and board[x][y]=='X':
                        dfs(board,x,y)
            
            res=0
            nr=len(board)
            if nr==0 :return 0
            nc=len(board[0])
            for i in range(nr):
                for j in range(nc):
                    if board[i][j]=='X':
                        res+=1
                        dfs(board,i,j)
            
            return res
    
  • 相关阅读:
    vue自定义指令
    ZOJ Problem Set–2104 Let the Balloon Rise
    ZOJ Problem Set 3202 Secondprice Auction
    ZOJ Problem Set–1879 Jolly Jumpers
    ZOJ Problem Set–2405 Specialized FourDigit Numbers
    ZOJ Problem Set–1874 Primary Arithmetic
    ZOJ Problem Set–1970 All in All
    ZOJ Problem Set–1828 Fibonacci Numbers
    要怎么样调整状态呢
    ZOJ Problem Set–1951 Goldbach's Conjecture
  • 原文地址:https://www.cnblogs.com/hqzxwm/p/14407825.html
Copyright © 2011-2022 走看看