题解 | #Sudoku#
Sudoku
https://www.nowcoder.com/practice/78a1a4ebe8a34c93aac006c44f6bf8a1
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 char[][] borad = new char[9][9]; String str = ""; while (in.hasNextLine()) { // 注意 while 处理多个 case for (int i = 0; i < borad.length; i++) { borad[i] = in.nextLine().replaceAll(" ", "").toCharArray(); } dfs(borad); for (int i = 0; i < borad.length; i++) { for (int j = 0; j < borad[0].length; j++) { System.out.print(borad[i][j] + " "); } System.out.println(); } } in.close(); } private static boolean dfs(char[][] borad) { // 行 for (int i = 0; i < borad.length; i++) { // 列 for (int j = 0; j < borad[0].length; j++) { if (borad[i][j] != '0') { continue; } for (char c = '1'; c <= '9'; c++) { if (isValid(i, j, c, borad)) { borad[i][j] = c; if (dfs(borad)) { return true; } borad[i][j] = '0'; } } return false; } } return true; } /** * 校验有效值 * @param row 行 * @param col 列 * @param val 填充值 * @param borad 9X9数独 * @return */ private static boolean isValid(int row, int col, int val, char[][] borad) { //行 for (int i = 0; i < 9; i++) { if (borad[row][i] == val) { return false; } } // 列 for (int i = 0; i < 9; i++) { if (borad[i][col] == val) { return false; } } // 每个3X3格子 int startRow = (row / 3) * 3; int startCol = (col / 3) * 3; for (int i = startRow; i < startRow + 3; i++) { for (int j = startCol; j < startCol + 3; j++) { if (borad[i][j] == val) { return false; } } } return true; } }#数独#