最近在学习Lua脚本,经过了不到十天的学习,也算是对语法有所了解吧,另外正好也看到了八皇后问题,感觉挺有意思的 就试了试用算法解出来。
八皇后问题的原题是:八皇后问题是一个以国际象棋为背景的问题:如何能够在 8×8 的国际象棋棋盘上放置八个皇后,使得任何一个皇后都无法直接吃掉其他的皇后?为了达到此目的,任两个皇后都不能处于同一条横行、纵行或斜线上。
以下是lua的算法代码:
local eightQueen = { 0,0,0,0,0,0,0,0,} local count = 0 function check(row,column) --检查 local data for i = 1,row do data = eightQueen[i] if column == data then --同列 return false elseif (i + data) == (row + column) then --/斜线 return false elseif (i - data) == (row - column) then --\斜线 return false end end return true end function eight_queen(row) for column = 1,8 do if check(row,column) == true then eightQueen[row] = column if row == 8 then count = count + 1 eightQueen[row] = 0 return end eight_queen(row + 1) eightQueen[row] = 0 end end end eight_queen(1) print(count)
#include<iostream> using namespace std; static int gEightQueen[8] = { 0 }, gCount = 0; void print()//输出每一种情况下棋盘中皇后的摆放情况 { for (int outer = 0; outer < 8; outer++) { for (int inner = 0; inner < gEightQueen[outer]; inner++) cout << "#"; for (int inner = gEightQueen[outer] + 1; inner < 8; inner++) cout << ""; cout << endl; } cout << "==========================\n"; } int check_pos_valid(int loop, int value)//检查是否存在有多个皇后在同一行/列/对角线的情况 { int index; int data; for (index = 0; index < loop; index++) { data = gEightQueen[index]; if (value == data) return 0; if ((index + data) == (loop + value)) return 0; if ((index - data) == (loop - value)) return 0; } return 1; } void eight_queen(int index) { int loop; for (loop = 0; loop < 8; loop++) { if (check_pos_valid(index, loop)) { gEightQueen[index] = loop; if (7 == index) { gCount++, print(); gEightQueen[index] = 0; return; } eight_queen(index + 1); gEightQueen[index] = 0; } } } int main(int argc, char*argv[]) { eight_queen(0); cout << "total=" << gCount << endl; return 0; }
原文地址:http://blog.csdn.net/nxshow/article/details/44096569