⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 queenrandom.java

📁 N皇后问题的实现
💻 JAVA
字号:
package yus.part2;

public class QueenRandom {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		long start = System.currentTimeMillis();

		int n = 54;
		int[] x = new int[n + 1];
		boolean success = false;
		while (success == false) {
			success = queensLV(n, x);
		}

		for (int i = 0; i < x.length; i++) {
			System.out.println("x[" + i + "]:" + x[i]);
		}

		long end = System.currentTimeMillis();
		System.out.println("time lasts " + (end - start) + "ms");
	}

	static boolean place(int k, int[] x) {
		for (int j = 1; j < k; j++) {
			if ((Math.abs(k - j) == Math.abs(x[j] - x[k])) || (x[j] == x[k]))
				return false;
		}
		return true;
	}

	static boolean queensLV(int n, int[] x) {
		int k = 1;
		int ok[] = new int[n + 1];
		int count;
		boolean success = false;
		while (k <= n) {
			count = 0;
			for (int i = 1; i <= n; i++) {
				x[k] = i;
				if (place(k, x) == true) {
					count++;
					ok[count] = i;
				}
			}
			if (count == 0) {
				success = false;
				break;
			} else {
				x[k] = ok[(int) (Math.random() * (count)) + 1];
				success = true;
			}
			k++;
		}
		return success;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -