# 1958. Check if Move is Legal

• Time: $O(1)$
• Space: $O(1)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class Solution { public: bool checkMove(vector>& board, int rMove, int cMove, char color) { const vector> dirs{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; for (const auto& [dx, dy] : dirs) { int cellsCount = 2; int i = rMove + dx; int j = cMove + dy; while (0 <= i && i < 8 && 0 <= j && j < 8) { // No free cells in between. if (board[i][j] == '.') break; // Need >= 3 cells. if (cellsCount == 2 && board[i][j] == color) break; // >= 3 cells. if (board[i][j] == color) return true; i += dx; j += dy; ++cellsCount; } } return false; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 class Solution { public boolean checkMove(char[][] board, int rMove, int cMove, char color) { final int[][] dirs = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; for (int k = 0; k < 8; ++k) { final int dx = dirs[k][0]; final int dy = dirs[k][1]; int cellsCount = 2; int i = rMove + dx; int j = cMove + dy; while (0 <= i && i < 8 && 0 <= j && j < 8) { // No free cells in between. if (board[i][j] == '.') break; // Need >= 3 cells. if (cellsCount == 2 && board[i][j] == color) break; // >= 3 cells. if (board[i][j] == color) return true; i += dx; j += dy; ++cellsCount; } } return false; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Solution: def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool: dirs = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] for dx, dy in dirs: cellsCount = 2 i = rMove + dx j = cMove + dy while 0 <= i < 8 and 0 <= j < 8: # No free cells in between. if board[i][j] == '.': break # Need >= 3 cells. if cellsCount == 2 and board[i][j] == color: break # >= 3 cells. if board[i][j] == color: return True i += dx j += dy cellsCount += 1 return False