Available Captures for Rook

Similar Problems:

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.

Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 3 Explanation: In this example the rook is able to capture all the pawns.

Input: [[".",".",".",".",".",".",".","."],[".","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",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 0 Explanation: Bishops are blocking the rook to capture any pawn.

Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 3 Explanation: The rook can capture the pawns at positions b5, d6 and f5.

Note:

- board.length
`= board[i].length =`

8 - board[i][j] is either ‘R’, ‘.’, ‘B’, or ‘p’
- There is exactly one cell with board[i][j] == ‘R’

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.

- Solution:

// https://code.dennyzhang.com/available-captures-for-rook // Basic Ideas: // Complexity: Time O(n*m), Space O(1) func numRookCaptures(board [][]byte) int { i, j := 0, 0 for ; i<len(board); i++ { j = 0 for ; j<len(board[i]); j++ { if board[i][j] == 'R' { break } } if j != len(board[i]) { break } } res := 0 for _, direction := range [][]int{[]int{0, 1}, []int{0, -1}, []int{1, 0}, []int{-1, 0}} { i2, j2 := i, j for i2>=0 && i2<len(board) && j2>=0 && j2<len(board[0]) { v := board[i2][j2] if v == 'B' { break } if v == 'p' { res++ break } i2, j2 = i2+direction[0], j2+direction[1] } } return res }