1. 程式人生 > >判斷簡單的數獨 java實現

判斷簡單的數獨 java實現

問題說明

我們實現是簡化的數獨,即數字全部輸入後,看數獨是否正確

程式碼

public class Progarm04 {
public static void main(String[] args) {
	int[][] grid = readASoulution();
	System.out.println(isValid(grid)?"Valid solution":"Invalid solution");
}

private static boolean isValid(int[][] grid) {
	for (int i = 0; i < grid.length;
i++) { for (int j = 0; j < grid.length; j++) { if(grid[i][j]<1||grid[i][j]>9 || !isValid(i,j,grid)) return false; } } return true; } private static boolean isValid(int i, int j, int[][] grid) { for (int col = 0; col < 9; col++) { if(col != j && grid[i][col]==grid[
i][j]) return false; } for (int row = 0; row < 9; row++) { if(row != i&& grid[row][j] == grid[i][j]) return false; } for (int row = (i/3)*3; row < (i/3)*3+3; row++) { for (int col = (j/3)*3; col < (j/3)*3+3; col++) { return false; } } return true; } private static
int[][] readASoulution() { Scanner input = new Scanner(System.in); System.out.println("Enter a Sudoku puzzle solution:"); int [][] grid = new int [9][9]; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid.length; j++) { grid[i][j] = input.nextInt(); } } return grid; } }