题解 | #Sudoku#
Sudoku
https://www.nowcoder.com/practice/78a1a4ebe8a34c93aac006c44f6bf8a1
import java.util.Scanner; public class Main { static final int N = 9; public static void main(String[] args) { Scanner in = new Scanner(System.in); int[][] sudoku = new int[N][N]; input(sudoku, in); backtrackSudoku(sudoku); output(sudoku); } static boolean backtrackSudoku(int[][] sudoku) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (sudoku[i][j] != 0) { continue; } for (int k = 1; k <= N; k++) { if (isValid(sudoku, i, j, k)) { sudoku[i][j] = k; if (backtrackSudoku(sudoku)) { return true; } sudoku[i][j] = 0; } } return false; } } return true; } static boolean isValid(int[][] sudoku, int i, int j, int val) { for (int k = 0; k < N; k++) { if (sudoku[k][j] == val || sudoku[i][k] == val) { return false; } } int m = (i / 3) * 3, n = (j / 3) * 3; for (int x = m; x < m + 3; x++) { for (int y = n; y < n + 3; y++) { if (sudoku[x][y] == val) { return false; } } } return true; } static void input(int[][] arr, Scanner in) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { arr[i][j] = in.nextInt(); } } } static void output(int[][] arr) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } }
#华为笔试#