八皇后问题

    xiaoxiao2021-12-14  20

    代码:

    // testlleet.cpp : 定义控制台应用程序的入口点。 #include "stdafx.h" #include <iostream> using namespace std; bool notDanger(int row, int col, int(*chess)[8]) { bool flag1 = 1, flag2 = 1, flag3 = 1, flag4 = 1;\ //判断当前列是否危险 for (int i = 0; i < row; i++) { if (*(*(chess + i) + col) == 1) flag1 = 0; } int row1 = row, col1 = col; //判断左上方 while (row1 != 0 && col1 != 0) { row1--;col1--; if (*(*(chess + row1) + col1) == 1) flag2 = 0; } row1 = row, col1 = col; //判断右上方 while (row1 != 0 && col1 != 7) { row1--; col1++; if (*(*(chess + row1) + col1) == 1) flag3 = 0; } row1 = row, col1 = col; //判断左下方 while (row1!= 7 && col1 != 0) { row1++; col1--; if (*(*(chess + row1) + col1) == 1) flag4 = 0; } if (flag1&flag2&flag3&flag4 == 1) return 1; else return 0; } void eightQueen(int row,int (*chess)[8],int &count) { //递归终止条件 if (row == 8) { count++; cout << "第" << count << "种方法:"<<endl; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { cout << *(*(chess + i) + j)<<" "; } cout << endl; } } else { //当前行从第一列开始扫描没有危险的位置 for (int i = 0; i < 8; i++) { if (notDanger(row, i,chess)) { *(*(chess + row) + i) = 1; eightQueen(row+1,chess,count); //继续向本行后面扫描前先复位 *(*(chess + row) + i) = 0; } } } } void main() { int chess[8][8]; int count = 0; // for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { *(*(chess + i) + j) = 0; } } //从第0行开始逐行放棋子 eightQueen(0,chess,count); cout << "一共有:" << count << "种方法"<<endl; system("pause"); }

    转载请注明原文地址: https://ju.6miu.com/read-970945.html

    最新回复(0)