【算法】用Lua解決八皇后的問題

最近在學習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)

思路照抄百度百科的C++代碼 C++代碼如下:

#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;
}

輸出如下:




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章