publicvoidsolve(char[][] board){ if (board == null || board.length == 0 || board[0].length == 0) { return; } int rowLen = board.length; int colLen = board[0].length; int[][] direct = newint[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; int directIndex = 0; int row = 0; int col = 0; boolean[][] visited = newboolean[rowLen][colLen]; // 顺时针遍历矩阵的边界 for (int i = 0; i <= ((rowLen + colLen) << 1) - 4; i++) { updateBoard(board, row, col, visited); int nextRow = row + direct[directIndex][0]; int nextCol = col + direct[directIndex][1]; if (nextRow < 0 || nextRow >= rowLen || nextCol < 0 || nextCol >= colLen) { directIndex = (directIndex + 1) % 4; } row += direct[directIndex][0]; col += direct[directIndex][1]; }
// 针对每个字母,如果这个字母被标记了,那么就保持原来的 'O',如果没有被标记,那么就置为 'X'。 for (int i = 0; i < rowLen; i++) { for (int j = 0; j < colLen; j++) { board[i][j] = visited[i][j] ? 'O' : 'X'; } } }
publicvoidupdateBoard(char[][] board, int x, int y, boolean[][] visited){ if (x < 0 || y < 0 || x >= board.length || y >= board[0].length || visited[x][y] || board[x][y] == 'X') { return; } visited[x][y] = true; updateBoard(board, x + 1, y, visited); updateBoard(board, x, y + 1, visited); updateBoard(board, x - 1, y, visited); updateBoard(board, x, y - 1, visited); }