[Swift Weekly Contest 125]LeetCode999. 车的可用捕获量 | Avai
在一个 8 x 8 的棋盘上,有一个白色车(rook)。也可能有空方块,白色的象(bishop)和黑色的卒(pawn)。它们分别以字符 “R”,“.”,“B” 和 “p” 给出。大写字符表示白棋,小写字符表示黑棋。 车按国际象棋中的规则移动:它选择四个基本方向中的一个(北,东,西和南),然后朝那个方向移动,直到它选择停止、到达棋盘的边缘或移动到同一方格来捕获该方格上颜色相反的卒。另外,车不能与其他友方(白色)象进入同一个方格。 返回车能够在一次移动中捕获到的卒的数量。 示例 1: 输入:[[".",".","."],[".","p","R","p"],"."]] 输出:3 解释: 在本例中,车能够捕获所有的卒。 示例 2: 输入:[[".","B","."]] 输出:0 解释: 象阻止了车捕获任何卒。 示例 3: 输入:[[".",["p","."]] 输出:3 解释: 车可以捕获位置 b5,d6 和 f5 的卒。 提示:
On an 8 x 8 chessboard,there is one white rook.? There also may be empty squares,white bishops,and black pawns.? These are given as characters ‘R‘,‘.‘,‘B‘,and ‘p‘ respectively. Uppercase characters represent white pieces,and lowercase characters represent black pieces. The rook moves as in the rules of Chess: it chooses one of four cardinal directions (north,east,west,and south),then moves in that direction until it chooses to stop,reaches the edge of the board,or captures an opposite colored pawn by moving to the same square it occupies.? Also,rooks cannot move into the same square as other friendly bishops. Return the number of pawns the rook can capture in one move. Example 1: Input: [[".","."]]
Output: 3 Explanation: In this example the rook is able to capture all the pawns.
Example 2: Input: [[".","."]]
Output: 0 Explanation: Bishops are blocking the rook to capture any pawn.
Example 3: Input: [[".","."]]
Output: 3 Explanation: The rook can capture the pawns at positions b5,d6 and f5.
Note:
Runtime:?12 ms
Memory Usage:?19.8 MB
1 class Solution { 2 func numRookCaptures(_ board: [[Character]]) -> Int { 3 var cnt:Int = 0 4 var n:Int = board.count 5 var m:Int = board[0].count 6 var x:Int = 0 7 var y:Int = 0 8 for i in 0..<n 9 { 10 for j in 0..<m 11 { 12 if board[i][j] == "R" 13 { 14 x = i 15 y = j 16 break 17 } 18 } 19 } 20 for i in stride(from:x - 1,through:0,by:-1) 21 { 22 if board[i][y] == "p" 23 { 24 cnt += 1 25 break 26 } 27 else if board[i][y] != "." 28 { 29 break 30 } 31 } 32 for i in (x + 1)..<n 33 { 34 if board[i][y] == "p" 35 { 36 cnt += 1 37 break 38 } 39 else if board[i][y] != "." 40 { 41 break 42 } 43 } 44 for j in stride(from:y - 1,by:-1) 45 { 46 if board[x][j] == "p" 47 { 48 cnt += 1 49 break 50 } 51 else if board[x][j] != "." 52 { 53 break 54 } 55 } 56 for j in (y + 1)..<m 57 { 58 if board[x][j] == "p" 59 { 60 cnt += 1 61 break 62 } 63 else if board[x][j] != "." 64 { 65 break 66 } 67 } 68 return cnt 69 } 70 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |