不要自卑,去提升实力
互联网行业谁技术牛谁是爹
如果文章可以带给你能量,那是最好的事!请相信自己,加油o~

题目描述:

判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。

检查数独是否有效(Java语言)_mysql

解题思路:

判断每个元素是否在1-9区间,再去判断重复
判断列重复,传入i j位置,除去a【i】【j】,其余行是否等于a【i】【j】
行重复同理
宫格重复可用 ( i / 3 )* 3 - ( i / 3 ) * 3+ 3

代码:

/**
*作者:魏宝航
*2020年11月28日,上午8:19
*/
import java.util.Scanner;
public class Test {

public static void main(String[] args) {
int[][] a = read();
boolean flag = judge(a);
if (flag)
System.out.println("合理");
else
System.out.println("不合理");

}

public static boolean judge(int[][] a) {
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
if (a[i][j] < 1 || a[i][j] > 9 || judge(i, j, a))
return false;
return true;
}

public static boolean judge(int i, int j, int[][] a) {
//检验行元素是否重复
for (int column = 0; column < 9; column++)
if (column != j && a[i][column] == a[i][j])
return true;
//检验列元素是否重复
for (int row = 0; row < 9; row++)
if (row != i && a[row][j] == a[i][j])
return true;
//检验每个方格元素是否重复
for (int row = (i / 3) * 3; row < (i / 3) * 3 + 3; row++)
for (int column = (j / 3) * 3; column < (j / 3) * 3 + 3; column++)
if (row != i && column != j && a[row][column] == a[i][j])
return true;
return false;
}

public static int[][] read() {
Scanner sc = new Scanner(System.in);
int[][] a = new int[9][9];
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
a[i][j] = sc.nextInt();
return a;
}

}