- 博客主页:音符犹如代码
- 系列专栏:算法练习
- 关注博主,后期持续更新系列文章
- 如果有错误感谢请大家批评指出,及时修改
- 感谢大家点赞👍收藏⭐评论✍
目录
思路
解题方法
时间复杂度
空间复杂度
Code
思路
- 首先将指定位置填充为给定颜色。然后针对八个方向进行合法性检查。
- 对于每个方向,调用一个专门的方法来计算中间不同颜色的数量,并判断是否构成好线段。
解题方法
- 通过提取
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;}
}