日期:2014-05-20 浏览次数:20758 次
void backtrace(int steps[],int depeth) { if(depth>=LIMIT){sloved();} constructCondicates(); foreach condicates do{ steps[depth]=condicates[i]; backtrace(depth++); } }
/** * @author yvon * */ public class TestGen { int constructCondicates(int steps[], int[] used, int level, int[] condicates) { int cn = 0; boolean has2 = false; for (int j = 0; j < 5; j++) { if (used[j] == 0) { if (level > 0) { if ((j == 2 && steps[level - 1] == 5) || (j == 4 && steps[level - 1] == 3) || (j == 3 && level == 2)) {// 三五不相连,四不能在第三位 continue; } } if (j == 1) { if (!has2) { has2 = true; } else {// 可行解里只能一次包含2.相同的位置(排除重复) continue; } } condicates[cn++] = j + 1; // 如果是2的话,还可以使用一次,前提是可行解没使用 } else if (j == 1 && !has2 && used[j] == 1) { condicates[cn++] = j + 1; has2 = true; } } return cn; } void doGen(int steps[], int used[], int level, int[] total) { if (level == 6) { for (int i = 0; i < 6; i++) { System.out.print(steps[i] + " "); } System.out.println(); total[0]++; return; } int condicates[] = new int[6]; int cn = constructCondicates(steps, used, level, condicates); for (int k = 0; k < cn; k++) { int todo = condicates[k]; steps[level] = todo; used[todo - 1]++; doGen(steps, used, level + 1, total); used[todo - 1]--; } } public static void main(String[] args) { int[] steps = new int[6]; int[] used = new int[6]; int total[] = new int[1]; new TestGen().doGen(steps, used, 0, total); System.out.println("Totally:" + total[0]); } }
1 2 2 3 4 5
1 2 2 5 4 3
1 2 3 2 4 5
1 2 3 2 5 4
1 2 3 4 2 5
1 2 3 4 5 2
1 2 5 2 3 4
1 2 5 2 4 3
1 2 5 4 2 3
1 2 5 4 3 2
1 3 2 2 4 5
1 3 2 2 5 4
1 3 2 4 2 5
1 3 2 4 5 2
1 3 2 5 2 4
1 3 2 5 4 2
1 4 2 3 2 5
1 4 2 5 2 3
1 4 3 2 2 5
1 4 3 2 5 2
1 4 5 2 2 3
1 4 5 2 3 2
1 5 2 2 3 4
1 5 2 2 4 3
1 5 2 3 2 4
1 5 2 3 4 2
1 5 2 4 2 3
1 5 2 4 3 2
2 1 2 3 4 5
2 1 2 5 4 3
2 1 3 2 4 5