目录
思路
- 首先将指定位置填充为给定颜色。然后针对八个方向进行合法性检查。
- 对于每个方向,调用一个专门的方法来计算中间不同颜色的数量,并判断是否构成好线段。
解题方法
- 通过提取
checkDirection
方法来处理对单个方向的检查逻辑,使得代码更具模块化和可读性。 - 在
checkDirection
方法中,通过循环和条件判断来统计中间颜色的数量,并根据情况决定是否构成好线段。
时间复杂度
O(1)
空间复杂度
O(1)
Code
class Solution {
public boolean checkMove(char[][] board, int rMove, int cMove, char color) {
board[rMove][cMove] = color;
int n = 8;
char between = color == 'W'? 'B' : 'W';
if (checkDirection(board, rMove, cMove, -1, 0, between) ||
checkDirection(board, rMove, cMove, 1, 0, between) ||
checkDirection(board, rMove, cMove, 0, -1, between) ||
checkDirection(board, rMove, cMove, 0, 1, between) ||
checkDirection(board, rMove, cMove, -1, -1, between) ||
checkDirection(board, rMove, cMove, 1, 1, between) ||
checkDirection(board, rMove, cMove, -1, 1, between) ||
checkDirection(board, rMove, cMove, 1, -1, between)) {
return true;
}
return false;
}
private boolean checkDirection(char[][] board, int r, int c, int dr, int dc, char between) {
int cnt = 0;
int row = r + dr;
int col = c + dc;
while (isValid(row, col) && board[row][col]!= '.') {
if (board[row][col] == between) {
cnt++;
} else if (board[row][col] == board[r][c]) {
if (cnt > 0) {
return true;
}
break;
}
row += dr;
col += dc;
}
return false;
}
private boolean isValid(int row, int col) {
return row >= 0 && row < 8 && col >= 0 && col < 8;
}
}