数独java

-1 2 6 -1 -1 -1 -1 -1 -1
-1 -1 -1 5 -1 2 -1 -1 4
-1 -1 -1 1 -1 -1 -1 -1 7
-1 3 -1 -1 2 -1 1 8 -1
-1 -1 -1 3 -1 9 -1 -1 -1
-1 5 4 -1 1 -1 -1 7 -1
5 -1 -1 -1 -1 1 -1 -1 -1
6 -1 -1 9 -1 7 -1 -1 -1
-1 -1 -1 -1 -1 -1 7 5 -1

结果:2358
思路:对行列作dfs,循环数字,换行用’/‘和’%'来决定

import java.util.Scanner;

public class Main {

	static int[][] map = new int[9][9];
	static int c = 1;
	public static boolean isVis(int n, int row, int col) {
		for (int i=0;i<9;i++) {
			if (n == map[row][i] || n == map[i][col])
				return false;
		}
		
		
		for (int i = (row/3)*3;i<(row/3)*3+3;i++)
			for (int j = (col/3)*3;j<(col/3)*3+3;j++)
				if (map[i][j] == n)
					return false;
		return true;
	}
	public static void dfs(int row, int col) {
		if (row == 9) {
			System.out.println("----第"+c+"方法-----");
			for (int i=0;i<9;i++) {
				for (int j = 0;j<9;j++)
					System.out.print(map[i][j]+" ");
				System.out.println();
			}
			c++;
			return;
		}
			
		
		if (map[row][col] == -1) {
			for (int i = 1; i<=9; i++) {
				if (isVis(i, row, col)) {
					map[row][col] = i;
					dfs(row + (col + 1)/9, (col + 1) %9);		
				}
				
			}
			map[row][col] = -1;
		}else {
			dfs(row + (col + 1)/9, (col + 1) %9);	
		}
		
		
		
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		for (int i=0;i<9;i++)
			for (int j = 0;j<9;j++)
				map[i][j] = sc.nextInt();
		dfs(0 ,0);
		
				


	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值