车的可用捕获量(3.26leetcode每日打卡)
在一个 8 x 8 的棋盘上,有一个白色车(rook)。也可能有空方块,白色的象(bishop)和黑色的卒(pawn)。它们分别以字符 “R”,“.”,“B” 和 “p” 给出。大写字符表示白棋,小写字符表示黑棋。
车按国际象棋中的规则移动:它选择四个基本方向中的一个(北,东,西和南),然后朝那个方向移动,直到它选择停止、到达棋盘的边缘或移动到同一方格来捕获该方格上颜色相反的卒。另外,车不能与其他友方(白色)象进入同一个方格。
返回车能够在一次移动中捕获到的卒的数量。
输入:[[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
输出:3
输出:3
输入:[[".",".",".",".",".",".",".","."],[".","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
解释:
象阻止了车捕获任何卒。
输出:0
解释:
象阻止了车捕获任何卒。
思路:题目很简单就是简单的遍历四个方向即可,主要是好好审题,比如抓到一个卒就可停止,好好审题方能事半功倍。
1 int numRookCaptures(char** board, int boardSize, int* boardColSize) 2 { 3 int cnt = 0; 4 int row,col; 5 int i,j; 6 7 //搜寻白色车所在位置 8 //车 R 9 //象 B 10 //卒 p 11 //空方格 . 12 for(i = 0; i < 8; i++) 13 { 14 for(j = 0; j < 8; j++) 15 { 16 if(board[i][j] == 'R') 17 { 18 row = i; 19 col = j; 20 break; 21 } 22 } 23 } 24 25 //搜寻右边 26 for(i = col+1; i < 8; i++) 27 { 28 if(board[row][i] == 'p') 29 { 30 cnt++; 31 break; 32 } 33 if(board[row][i] == 'B') 34 break; 35 } 36 37 //搜寻左边 38 for(i = col-1; i >= 0; i--) 39 { 40 if(board[row][i] == 'p') 41 { 42 cnt++; 43 break; 44 } 45 if(board[row][i] == 'B') 46 break; 47 } 48 49 //搜寻下边 50 for(i = row+1; i < 8; i++) 51 { 52 if(board[i][col] == 'p') 53 { 54 cnt++; 55 break; 56 } 57 if(board[i][col] == 'B') 58 break; 59 } 60 61 //搜寻上边 62 for(i = row-1; i >= 0; i--) 63 { 64 if(board[i][col] == 'p') 65 { 66 cnt++; 67 break; 68 } 69 if(board[i][col] == 'B') 70 break; 71 } 72 return cnt; 73 }