Lecture Videos
  1  import java.util.Scanner;
  2  
  3  public class CheckSudokuSolution {
  4    public static void main(String[] args) {
  5      // Read a Sudoku solution
  6      int[][] grid = readASolution();
  7  
  8      System.out.println(isValid(grid) ? "Valid solution" 
  9        : "Invalid solution");
 10    }
 11  
 12    /** Read a Sudoku solution from the console */
 13    public static int[][] readASolution() {
 14      // Create a Scanner
 15      Scanner input = new Scanner(System.in);
 16  
 17      System.out.println("Enter a Sudoku puzzle solution:");
 18      int[][] grid = new int[9][9];
 19      for (int i = 0; i < 9; i++)
 20        for (int j = 0; j < 9; j++)
 21          grid[i][j] = input.nextInt();
 22  
 23      return grid;
 24    }
 25  
 26    /** Check whether a solution is valid */
 27    public static boolean isValid(int[][] grid) {
 28      for (int i = 0; i < 9; i++)
 29        for (int j = 0; j < 9; j++)
 30          if (grid[i][j] < 1 || grid[i][j] > 9 
 31              || !isValid(i, j, grid))
 32            return false;
 33      return true; // The solution is valid
 34    }
 35  
 36    /** Check whether grid[i][j] is valid in the grid */
 37    public static boolean isValid(int i, int j, int[][] grid) {
 38      // Check whether grid[i][j] is valid at the i's row
 39      for (int column = 0; column < 9; column++)
 40        if (column != j && grid[i][column] == grid[i][j])
 41          return false;
 42  
 43      // Check whether grid[i][j] is valid at the j's column
 44      for (int row = 0; row < 9; row++)
 45        if (row != i && grid[row][j] == grid[i][j])
 46          return false;
 47  
 48      // Check whether grid[i][j] is valid in the 3 by 3 box
 49      for (int row = (i / 3) * 3; row < (i / 3) * 3 + 3; row++)
 50        for (int col = (j / 3) * 3; col < (j / 3) * 3 + 3; col++)
 51          if (!(row == i && col == j) && grid[row][col] == grid[i][j])
 52            return false;
 53  
 54      return true; // The current value at grid[i][j] is valid
 55    }
 56  }