[LeetCode] 999. Available Captures for Rook
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.
可以被一步捕获的棋子数。题意是给一个棋盘,你可以控制白色的车,用字符R表示,棋盘上其他白色的棋子用大写字母表示,其他黑色的棋子用小写字母表示,求问棋盘上你的车能一步吃掉的卒(小写p)有几个。比如这个例子,车能吃掉3个卒。
这个题没有什么算法,就是按规则从车所在的位置开始扫描4个不同的方向,遇到小写的p则res++,遇到边缘和大写的字母(因为是白色棋子)则停下。这个题也是训练你在矩阵中如何一直往一个方向走的技巧,还是蛮有意思的一道题。
时间O(64) - 最极端情况需要扫描整个棋盘
空间O(1)
Java实现
1 class Solution { 2 public int numRookCaptures(char[][] board) { 3 // 定义上下左右四个方向 4 int[] dx = { -1, 1, 0, 0 }; 5 int[] dy = { 0, 0, -1, 1 }; 6 7 for (int i = 0; i < 8; i++) { 8 for (int j = 0; j < 8; j++) { 9 // 找到白车所在的位置 10 if (board[i][j] == 'R') { 11 // 分别判断白车的上、下、左、右四个方向 12 int res = 0; 13 for (int k = 0; k < 4; k++) { 14 int x = i, y = j; 15 while (true) { 16 x += dx[k]; 17 y += dy[k]; 18 if (x < 0 || x >= 8 || y < 0 || y >= 8 || board[x][y] == 'B') { 19 break; 20 } 21 if (board[x][y] == 'p') { 22 res++; 23 break; 24 } 25 } 26 } 27 return res; 28 } 29 } 30 } 31 return 0; 32 } 33 }
JavaScript实现
1 /** 2 * @param {character[][]} board 3 * @return {number} 4 */ 5 var numRookCaptures = function(board) { 6 let dx = [-1, 1, 0, 0]; 7 let dy = [0, 0, -1, 1]; 8 for (let i = 0; i < 8; i++) { 9 for (let j = 0; j < 8; j++) { 10 if (board[i][j] == 'R') { 11 let res = 0; 12 for (let k = 0; k < 4; k++) { 13 let x = i; 14 let y = j; 15 while (true) { 16 x += dx[k]; 17 y += dy[k]; 18 if ( 19 x < 0 || 20 x >= 8 || 21 y < 0 || 22 y >= 8 || 23 board[x][y] == 'B' 24 ) { 25 break; 26 } 27 if (board[x][y] == 'p') { 28 res++; 29 break; 30 } 31 } 32 } 33 return res; 34 } 35 } 36 } 37 return 0; 38 };