1 2 3 4 5 6 7 8 9 10 | void backtrace(int steps[],int depeth) { if(depth>=LIMIT){sloved();} constructCondicates(); foreach condicates do{ steps[depth]=condicates; backtrace(depth++); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | /** * @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 + " "); } 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]); } } 学习中! |
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |