您好,登錄后才能下訂單哦!
小編給大家分享一下leetcode中如何解決車的可用捕獲量問題,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
車的可用捕獲量
在一個 8 x 8 的棋盤上,有一個白色車(rook)。也可能有空方塊,白色的象(bishop)和黑色的卒(pawn)。它們分別以字符 “R”,“.”,“B” 和 “p” 給出。大寫字符表示白棋,小寫字符表示黑棋。
車按國際象棋中的規則移動:它選擇四個基本方向中的一個(北,東,西和南),然后朝那個方向移動,直到它選擇停止、到達棋盤的邊緣或移動到同一方格來捕獲該方格上顏色相反的卒。另外,車不能與其他友方(白色)象進入同一個方格。
返回車能夠在一次移動中捕獲到的卒的數量。
示例 1:
輸入:
[[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
輸出:3
解釋:
在本例中,車能夠捕獲所有的卒。
示例 2:
輸入:
[[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
輸出:0
解釋:
象阻止了車捕獲任何卒。
示例 3:
輸入:
[[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]]
輸出:3
解釋:
車可以捕獲位置 b5,d6 和 f5 的卒。
提示:
board.length == board[i].length == 8
board[i][j] 可以是 'R','.','B' 或 'p'
只有一個格子上存在 board[i][j] == 'R'
思路:
題目的意思是中間R走一下能吃p的次數,方向是上下左右四個方向
限制條件是走一次,以及遇到B就表明該方向不通
class Solution: def numRookCaptures(self, board: List[List[str]]) -> int: cnt, st, ed = 0, 0, 0 # 方向數組 direction = [(0, 1), (0, -1), (1, 0), (-1, 0)] # 找到R for i in range(8): for j in range(8): if board[i][j] == 'R': st = i ed = j # 朝著四個方向探索 for i in range(4): step = 0 while True: dx, dy = direction[i] tx = st + step * dx ty = ed + step * dy if tx < 0 or tx >= 8 or ty < 0 or ty >= 8 or board[tx][ty] == 'B': break if board[tx][ty] == 'p': cnt += 1 break step += 1 #每次移動的范圍,第一次移動一格,找不到的話移動兩格 return cnt
看完了這篇文章,相信你對“leetcode中如何解決車的可用捕獲量問題”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。