Leetcode-999 Available Captures for Rook(车的可用捕获量)

作者水平有限,所发仅为个人愚见,如有明显谬误,望斧正

这是一道随便搞搞就能过的模拟题,看到的时候我没有想太多,直接搜过去了——先找到白车位置,然后东南西北四个方向看一下离白车最近的是己方还是敌方棋子,己方棋子就跳出循环,敌方棋子让结果变量cnt自增1以后跳出循环。cnt只有可能是{0,1,2,3,4}中的一个数。之所以敢这么做的原因是board是一个标准的国际象棋board,长宽必定都是8,所以复杂度可以说是O(1)的,最坏的情况的搜索数必定小于4*8次。

 1 #define pb push_back
 2 #define maxSize 3939
 3 #define _for(i,a,b) for(int i = (a);i < (b);i ++)
 4 
 5 class Solution
 6 {
 7     public:
 8         bool islimited(vector<vector<char>>& board,int x,int y)
 9         {
10             if(x>=0&&x<8&&y>=0&&y<8&&board[x][y]!='B')
11                 return true;
12             return false;
13         }
14         int numRookCaptures(vector<vector<char>>& board)
15         {
16             int x,y;
17             _for(i,0,8)
18                 _for(j,0,8)
19                     if(board[i][j]=='R')
20                     {
21                         x = i;
22                         y = j;
23                         break;
24                     }
25             
26             int cnt = 0;
27             for(int i = x-1;islimited(board,i,y);i --)
28             {
29                 if(board[i][y]=='p')
30                 {
31                     cnt ++;
32                     break;
33                 }
34             }
35             
36             for(int i = x+1;islimited(board,i,y);i ++)
37             {
38                 if(board[i][y]=='p')
39                 {
40                     cnt ++;
41                     break;
42                 }
43             }
44             
45             for(int i = y-1;islimited(board,x,i);i --)
46             {
47                 if(board[x][i]=='p')
48                 {
49                     cnt ++;
50                     break;
51                 }
52             }
53             
54             for(int i = y+1;islimited(board,x,i);i ++)
55             {
56                 if(board[x][i]=='p')
57                 {
58                     cnt ++;
59                     break;
60                 }
61             }
62             return cnt;
63         }
64 };
Leetcode-999(C++)

 执行用时:8ms

原文地址:https://www.cnblogs.com/Asurudo/p/10427919.html