码迷,mamicode.com
首页 > 其他好文 > 详细

9*9宫格数独

时间:2017-11-11 14:12:01      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:checkbox   number   key   main   +=   log   重复数   func   final   

public class NumberDegrees {
	
	private final static int N = 3;
	public static void main(String[] args) {
		
		 int x[][]={
                 {0,2,0,0,0,9,0,1,0,0},
                 {5,0,6,0,0,0,3,0,9,0},
                 {0,8,0,5,0,2,0,6,0,0},
                 {0,0,5,0,7,0,1,0,0,0},
                 {0,0,0,2,0,8,0,0,0,0},
                 {0,0,4,0,1,0,8,0,0,0},
                 {0,5,0,8,0,7,0,3,0,0},
                 {7,0,2,3,0,0,4,0,5,0},
                 {0,4,0,0,0,0,0,7,0,0},
         };
		 NumberDegrees number = new NumberDegrees();
		 number.function(x,0,0);
		
	}
	
	
	public void function(int[][] x, int r, int c) {
		//1.判断行数,如果是第九行或者大与9行的话直接输出数独
		if (r >= x.length) {
			show(x);
			return;
		}
		//2.判断如果是3,6,9行的话判断前面的几行是否有重复数字
		if (c == 0 && (r == x.length / 3 || r == x.length / 3 * 2 || r == x.length)) {
			if(!checkBox(x, r)) {
				return;
			}
		}
		//3.判断是否是一行的最后一列,如果是,则跳转到下一行
		if (c >= x.length) {
			function(x, r + 1, 0);
			return;
		}
		//4.判断是否是需要填的数字,如果是则填写正确的数字,如果不是则填写下一个
		if (x[r][c] == 0) {
			for (int i = 1; i <= x.length; i++) {
				if(checked(x, r, c, i)) {
					x[r][c] = i;
					function(x, r, c + 1);
					x[r][c] = 0;		
				}
			}
			
		} else {
			function(x, r, c + 1);
		}
	}
	/**
	 * 判断这列这行的是否有数字与之相等
	 * @param x
	 * @param r
	 * @param c
	 * @param i
	 * @return
	 */
	public boolean checked(int[][] x, int r, int c, int i) {
		for (int j = 0; j < x.length; j++) {
			if(x[r][j] == i) {
				return false;
			} 
			if (x[j][c] == i) {
				return false;
			}
		}
		
		return true;
	}

	
	/**
	 * 判断前几行是否有重复的数字
	 * @param x
	 * @param r
	 * @return
	 */
	public boolean checkBox(int [][] x, int r) {
		for (int k = 0; k < x.length; k += x.length / N) {
			Map<Integer, Integer> map = new HashMap<Integer, Integer>();
			for (int i = r - N; i < r; i++) {
				for (int j = k; j < k + x.length / N; j++) {
					if (map.containsKey(x[i][j])) {
						return false;
					}
					map.put(x[i][j], 1);
				}
			}
		}
		
		return true;
	}

	public void show(int[][] x) {
		for (int i = 0; i < x.length; i++) {
			for (int j = 0; j < x.length; j++) {
				System.out.print(x[i][j] + " ");
			}
			System.out.println();
		}
		System.out.println();
	}

}

  

9*9宫格数独

标签:checkbox   number   key   main   +=   log   重复数   func   final   

原文地址:http://www.cnblogs.com/wangxiaowang/p/7818808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!