首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

1维数组,N皇后

2012-09-15 
一维数组,N皇后?import java.util.Arrayspublic class test {public static void main(String[] args) {n

一维数组,N皇后

?

import java.util.Arrays;public class test {public static void main(String[] args) {new test();}int count = 0;public test() {int N = 6;int[] a = new int[N];a[0] = -1;for (int i = 0; i < N; i++) {Arrays.fill(a, 1, N, -1);find(0, a, N);}System.out.println(count);}public void find(int row, int[] a, int length) {a[row]++;for (int i = 0; i <= row - 1; i++) {if (a[i] == a[row]) {return;}if (Math.abs(i - row) == Math.abs(a[i] - a[row])) {return;}}if (row + 1 < length) {for (int i = 0; i < length; i++) {Arrays.fill(a, row + 2, length, -1);find(row + 1, a, length);}} else {for (int i = 0; i < length; i++) {System.out.print(a[i] + "\t");}System.out.println();count++;}}}

N皇后的解的个数,可以参考:

http://bbs.ednchina.com/BLOG_ARTICLE_2129140.HTM

热点排行