N皇后:JAVA的递归实现(回溯法)

  • 题目
    所谓N皇后问题就是:将N位皇后放在一张NxN的棋盘上,使得每位皇后都无法吃掉别的皇后,(即任意两个皇后都不在同一条横线,竖线和斜线上),问一共有多少种摆法。
  • 实现及思路
package 蓝桥;

import java.util.Scanner;

public class NQueen {
		static int count = 0;//解法计数
		static int[][] arry ;//棋盘
		static int n;//皇后数
		public static void findQueen(int row) {
			if (row == n) {
			//搜寻到最后一行,每搜寻完一次将解法输出
				count++;
				print();
				return;
			}
			for (int coulm = 0; coulm < n; coulm++) {
			//可行即置为1表示占位
				if (cheack(row, coulm)) {
					arry[row][coulm] = 1;
					//放置下一个皇后
					findQueen(row + 1);
					//当下一个皇后无处可放的情况时执行,将此处的皇后清除
					//若没有发生这种情况,将不会执行,直接通过return结束
					arry[row][coulm] = 0;
				}
			}

		}

		public static void print() {
			System.out.println("第" + count + "种方法:");
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < n; j++) {
					if (arry[i][j] == 1)
						System.out.print("O ");
					else
						System.out.print("+ ");
				}
				System.out.println();
			}
			System.out.println();
		}

		public static boolean cheack(int a, int b) {
			for (int i = 0; i < n; i++) {
				//列测试
				if (arry[i][b] == 1)
					return false;
			}
			for (int i = a - 1, j = b - 1; i >= 0 & j >= 0; i--, j--) {
				//左对角线
				if (arry[i][j] == 1)
					return false;
			}
			for (int i = a - 1, j = b + 1; i >= 0 & j < n; i--, j++) {
				//右对角线
				if (arry[i][j] == 1)
					return false;
			}
			return true;
		}

		public static void main(String[] args) {
			Scanner sc=new Scanner(System.in);
			n=sc.nextInt();
			arry=new int[n][n];
			long startTime = System.currentTimeMillis();
			findQueen(0);
			System.out.println("共"+count+"种方法");
			long endTime = System.currentTimeMillis(); // 获取结束时间
			System.out.println("程序运行时间:" + (endTime - startTime) + "ms");
		}
	}


  • 结果
    在这里插入图片描述
    在这里插入图片描述在这里插入图片描述
发布了41 篇原创文章 · 获赞 1 · 访问量 1484

猜你喜欢

转载自blog.csdn.net/qq_44467578/article/details/103912440