Skip to content

Commit 2fffbd7

Browse files
authored
Add solution 02 and 03
1 parent 650b15e commit 2fffbd7

File tree

1 file changed

+56
-1
lines changed

1 file changed

+56
-1
lines changed

0999. Available Captures for Rook

+56-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ There is exactly one cell with board[i][j] == 'R'
7676
****************************************/
7777

7878

79-
/***** Solution_01 *****/
79+
/***************************************** Solution_01 ****************************************/
8080

8181
class Solution {
8282
public int numRookCaptures(char[][] board) {
@@ -135,9 +135,64 @@ class Solution {
135135

136136

137137

138+
/**************************************** Solution_02 ****************************************/
138139

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+
}
139161

140162

141163

142164

165+
/**************************************** Solution_03 ****************************************/
143166

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

Comments
 (0)