数字积木--dfs

字,0~9。

搭积木规则:
每个积木放到其它两个积木的上面,并且一定比下面的两个积木数字小。
最后搭成4层的金字塔形,必须用完所有的积木。

下面是两种合格的搭法:

   0
  1 2
 3 4 5
6 7 8 9

   0
  3 1
 7 5 2
9 8 6 4    

请你计算这样的搭法一共有多少种?

package com.xjj.lqtest;
/*----数字积木----
 * 
 * */
public class Digital_build {
	public int[] a  = new int[10];
	public int[] book = new int[10];
	public static int count = 0;
	
	public void dfs(int n){
		if (n == a.length)				//全部排满
			if (check(a)) {
				count++;
				return;
			}

		for(int i = 1; i <= 9; i++)
			if (book[i] == 0) {
				a[n] = i;
				book[i] = 1;
				dfs(n+1);				//不能用n++
				book[i] = 0;

			}
	}
	
	public boolean check(int[] a){
		if (a[1] > a[0] && a[2] > a[0]) 
			if (a[3] > a[1] && a[4] > a[1] && a[5] > a[2] && a[4] > a[2]) 
				if (a[6] > a[3] && a[7] > a[3] && a[7] > a[4] && a[8] > a[4]) 
					if (a[8] > a[5] && a[9] > a[5]) 
						return true;
		return false;

	}

	public static void main(String[] args) {
		Digital_build dig = new Digital_build();
		dig.dfs(1);
		System.out.println(count);

	}

}

猜你喜欢

转载自blog.csdn.net/jiejiexiao/article/details/79718997
今日推荐