问题:
给定国际象棋二维数组,
B代表阻止,p代表可吃点,R代表起始点。
从R开始向上下左右直线移动,遇到p点,res+1。遇到B或者棋盘边界res不增不减。
求最后res的值。
Example 1: Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]] Output: 3 Explanation: In this example the rook is able to capture all the pawns. Example 2: 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. Example 3: 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'
解法:
先遍历二维数组,找到R
然后向四个方向找到 p:res+1
找到 边界 or B 停止寻找。
代码参考:
1 class Solution { 2 public: 3 int findp(vector<vector<char>>& board, int i, int j, int pi, int pj){ 4 while(i>=0 && i<board.size() && j>=0 && j<board[0].size() 5 && board[i][j] != 'B'){ 6 if(board[i][j]=='p') return 1; 7 i+=pi; 8 j+=pj; 9 } 10 return 0; 11 } 12 13 int numRookCaptures(vector<vector<char>>& board) { 14 int res=0; 15 int n=board.size(), m=board[0].size(); 16 for(int i=0; i<n; i++){ 17 for(int j=0; j<m; j++){ 18 if(board[i][j]=='R'){ 19 res=findp(board, i, j, 1, 0)+findp(board, i, j, -1, 0)+ 20 findp(board, i, j, 0, 1)+findp(board, i, j, 0, -1); 21 } 22 } 23 } 24 return res; 25 } 26 };