标签:六角幻方
标题:六角幻方这是一行用空格分开的整数,请通过浏览器提交答案,不要填写任何多余的内容(比如说明性的文字等)
解题思路: DFS
源代码:
/** * * 六角幻方搜索 * * */ public class Main1 { static int table[] = {1,2,3,4,5,6,7,8,9,10,11,12,14,16,17,18,19}; //内容 public static void main(String[] args) { int arr[] = new int[17]; boolean step[]= new boolean[20]; step[15] = step[13] = true; dfs(arr, 0, step); } private static void dfs(int[] arr, int ws, boolean[] step) { if (ws == 5) { if (28 + arr[0] != arr[1] + arr[2] + arr[3] + arr[4])return; } if (ws == 6) { if (28 + arr[0] != 15 + arr[1] + arr[5]) return ; } if (ws == 10) { if (28 + arr[0] != arr[5] + arr[6] + arr[7] + arr[8] + arr[9])return; if (28 + arr[0] != arr[0] + arr[4] + arr[9]) return; } if (ws == 11) { if (28 + arr[0] != 13 + arr[2] + arr[6] + arr[10]) return; } if (ws == 14) { if (28 + arr[0] != arr[10] + arr[11] + arr[12] + arr[13])return; if (28 + arr[0] != 13 + arr[3] + arr[8] + arr[13]) return; } if (ws == 15) { if (28 + arr[0] != arr[5] + arr[10] + arr[14]) return; if (28 + arr[0] != arr[0] + arr[3] + arr[7] + arr[11]+arr[14])return; } if (ws == 17) { if (28 + arr[0] != arr[14] + arr[15]+arr[16]) return; if (28 + arr[0] !=15+ arr[2]+arr[7] + arr[12]+arr[16]) return; if (28 + arr[0] != arr[9] + arr[13] + arr[16]) return; output(arr);return; } for (int i = 0; i < table.length; i++) { if (step[table[i]] == false) { step[table[i]] = true; arr[ws] = table[i]; dfs(arr, ws+1, step); step[table[i]] = false; } } } private static void output(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } }
标签:六角幻方
原文地址:http://blog.csdn.net/first_sight/article/details/44530613