{"title": "C++ N皇后问题代码优化:找出代码中的12个错误", "description": "本文分析了一段用于解决N皇后问题的C++代码,并详细指出了代码中的12个错误,并提供了相应的修改建议。", "keywords": "N皇后问题, C++, 代码优化, 算法, 编程", "content": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define inlimit(x, y) ((x) >= 0 && (x) <= size-1 && (y) >= 0 && (y) <= size-1)\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(target == 0 && inlimit(thisRow, loc)){\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 thisRow++;\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 return true;\n } else\n return false;\n }\n void next(){\n Solution newSolution = *this;\n for(size_t i = 0; i < size; ++i){\n if( newSolution.addQueen(i) ){\n newSolution.next();\n }\n }\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 int x;\n cin >> x;\n solution.solute((size_t)x);\n return 0;\n}\n"\n

C++ N皇后问题代码优化:找出代码中的12个错误

原文地址: https://www.cveoy.top/t/topic/pBhB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录