Sudoku, implemented in java

1. Introduction

The program calls the readSolutionO method to read a Sudoku solution and returns a two-dimensional array representing the Sudoku grid. The isValid(grid) method confirms whether the correct value is placed in the grid by checking whether each value is a number from 1 to 9 and whether the value in each grid is valid. The isValid(i,j.grid) method checks whether the value of grid[i][j] is valid. It checks whether grid[i][;j] appears more than once in the i-th row, j-th column, and 3x3 square box.

2. Code

package com.zhuo.base;

import java.util.Scanner;

public class CheckSudocuSolution {
    
    
    public static void main(String[] args) {
    
    
        int[][] grid = readSolution();//读取数独解
        System.out.println(isvalid(grid) ? "valid solution" : "invalid solution");
    }
    /*从控制台读取数独解决方案*/
    public static int[][] readSolution() {
    
    
        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 < 9; i++) {
    
    
            for (int j = 0; j <9; j++)
                grid[i][j] = input.nextInt();
        }
        return grid;
    }
    /*检查解决方案是否有效*/
    public static boolean isvalid(int[][] grid) {
    
    
        for (int i = 0; i < 9; i++) {
    
    
            for (int j = 0; j < 9; j++)
                if (grid[i][j] < 0 || grid[i][j] > 9 || !isvalid(i, j, grid))
                    return false;
        }
        return true;
    }
    public static boolean isvalid(int i, int j, int[][] grid) {
    
    
        /*检查网格[i][j]在j的行中是否唯一*/
        for (int row = 0; row < 9; row++)
            if (row != i && grid[row][j] == grid[i][j])
                return false;
            /*检查网格[i][j]在i的行中是否唯一*/
        for (int column = 0; column < 9; column++)
            if (column != j && grid[i][column] == 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++)
                if (row != i && col != j && grid[row][col] == grid[i][j])
                    return false;
        return true;
    }
}

3. Results achieved

Enter a sudoku puzzle solution: 
9 6 3 1 7 4 2 5 8
1 7 8 3 2 5 6 4 9
2 5 4 6 8 9 7 3 1
8 2 1 4 3 7 5 9 6
4 9 6 8 5 2 3 1 7
7 3 5 9 6 1 8 2 4
5 8 9 7 1 3 4 6 2
3 1 7 2 4 6 9 8 5
6 4 2 5 9 8 1 7 3
valid solution

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/weixin_42768634/article/details/113731465