@@ -76,7 +76,7 @@ There is exactly one cell with board[i][j] == 'R'
76
76
****************************************/
77
77
78
78
79
- /***** Solution_01 *****/
79
+ /***************************************** Solution_01 *********************************** *****/
80
80
81
81
class Solution {
82
82
public int numRookCaptures(char[][] board) {
@@ -135,9 +135,64 @@ class Solution {
135
135
136
136
137
137
138
+ /**************************************** Solution_02 ****************************************/
138
139
140
+ class Solution {
141
+ public int numRookCaptures(char[][] board) {
142
+ for (int i = 0; i < board.length; ++i) {
143
+ for (int j = 0; j < board[i].length; ++j) {
144
+ if (board[i][j] == 'R')
145
+ return cap(board,i,j,0,1)+cap(board,i,j,0,-1)+cap(board,i,j,1,0)+cap(board,i,j,-1,0);
146
+ }
147
+ }
148
+ return 0;
149
+ }
150
+
151
+ private int cap(char[][] board, int x, int y, int r, int c) {
152
+ while (x >= 0 && x < board.length
153
+ && y >= 0 && y < board[x].length
154
+ && board[x][y] != 'B') {
155
+ if (board[x][y] == 'p') {return 1;}
156
+ x += r; y += c;
157
+ }
158
+ return 0;
159
+ }
160
+ }
139
161
140
162
141
163
142
164
165
+ /**************************************** Solution_03 ****************************************/
143
166
167
+ class Solution {
168
+ public int numRookCaptures(char[][] board) {
169
+ int[] point = new int[2];
170
+ int row = board.length;
171
+ int col = board[0].length;
172
+
173
+ for(int i = 0 ; i < row ; i++) {
174
+ for(int j = 0 ; j < col ; j++) {
175
+ if(board[i][j] == 'R') {
176
+ point[0] = i;
177
+ point[1] = j;
178
+ break;
179
+ }
180
+ }
181
+ }
182
+
183
+ int result = 0;
184
+ int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
185
+
186
+ for(int[] dir : dirs) {
187
+ int x = point[0] + dir[0];
188
+ int y = point[1] + dir[1];
189
+ while(x >= 0 && y >= 0 && x < row && y < col && board[x][y] == '.') {
190
+ x += dir[0];
191
+ y += dir[1];
192
+ }
193
+ if(x < 0 || y < 0 || x >= row || y >= col) continue;
194
+ if(board[x][y] == 'p') {result++;}
195
+ }
196
+ return result;
197
+ }
198
+ }
0 commit comments