C++ N皇后问题代码优化:找出代码中的9个问题
{///'title///': ///'C++ N皇后问题代码优化:找出代码中的9个问题///', ///'description///': ///'本文分析了一份用于解决N皇后问题的C++代码,并列举了代码中的9个问题,并提供了相应的解决方案。///', ///'keywords///': ///'N皇后问题, C++, 代码优化, 算法, 回溯///', ///'content///': ///'#include<bits/stdc++.h>//nusing namespace std;//n//n#define inlimit(x, y) ((x) >= 0 && (x) < size && (y) >= 0 && (y) < size)//n#define check_than_do(x, y) if(checkboard[(x)][(y)] >= 0) checkboard[(x)][(y)]++//n#define if_inlimit_check_than_do(x, y) if( inlimit( (x), (y) ) ) check_than_do ( (x), (y) ); //n//nclass Solution{//nprivate://n static const size_t MAXIMUM = 16;//n //n int checkboard[MAXIMUM][MAXIMUM];//n size_t thisRow;//n size_t size;//n //n void reset(){//n memset(checkboard, 0, sizeof(checkboard));//n thisRow = 0;//n size = 0;//n }//n //n bool addQueen(size_t loc){//n int& target = checkboard[thisRow][loc];//n if( inlimit(thisRow, loc) && target == 0 ){//n target = -1; //标记皇后//n //n for(size_t i = 0; i < size; ++i){//n if_inlimit_check_than_do(thisRow, i); //棋子左右//n if_inlimit_check_than_do(i, loc); //棋子上下//n if_inlimit_check_than_do(thisRow+i, loc+i); //棋子右下//n if_inlimit_check_than_do(thisRow-i, loc-i); //棋子左上//n if_inlimit_check_than_do(thisRow+i, loc-i); //棋子左下//n if_inlimit_check_than_do(thisRow-i, loc+i); //棋子右上//n }//n if(thisRow >= size){//n for(size_t i = 0; i < size; ++i){//n for(size_t j = 0; j < size; ++j)//n if(checkboard[i][j] == -1){//n cout << j+1 << ' ' ;//n break;//n }//n cout << endl;//n }//n return false;//n }//n thisRow++;//n return true;//n } else//n return false;//n }//n void next(){//n Solution* newSolution = new Solution();//n newSolution->solute(size); //重置newSolution状态//n for(size_t i = 0; i < size; ++i){//n *newSolution = *this;//n if( newSolution->addQueen(i) )//n newSolution->next();//n }//n delete newSolution;//n }//npublic://n void solute(size_t n){//n reset();//n size = n;//n next();//n }//n};//n//n//nint main(){//n Solution solution;//n size_t x;//n cin >> x;//n if(x >= 1 && x <= 10){ //合法性判断//n solution.solute(x-1); //输入n,而不是n-1//n }//n return 0;//n}//n/
原文地址: https://www.cveoy.top/t/topic/pBhZ 著作权归作者所有。请勿转载和采集!