有關西洋棋盤騎士路徑ㄉ問題 |
尚未結案
|
kie
一般會員 ![]() ![]() 發表:1 回覆:0 積分:0 註冊:2003-09-13 發送簡訊給我 |
|
daniel__lee
高階會員 ![]() ![]() ![]() ![]() 發表:18 回覆:124 積分:113 註冊:2002-11-10 發送簡訊給我 |
伱的問題再演算法書中應該找的到 這是我書上的皇后問題
由於篇幅蠻大的我只key其中的一小部分 希望對你有幫助
The Backtracking Algorithm for the n-Queens Problem: (cont.)
The promising function must check whether two queens are in the same column or diagonal. If let col(i) be the column where the queen in the ith row is located, then, to check whether the queen in the kth row is in the same column, we need to check whether col(i) = col(k).
Next check the diagonal, for the queen threatening from the left, the difference in the column is the same as the difference in the rows.
These are examples of the general result that if the queen in the kth row threatens the queen in the ith row along one of its diagonals, then
col(i) – col(k) = i – k or col(i) – col(k) = k – i
---------------------------------------------------------------------
P: Position n queens on a chessboard so that no two are in the same row, column, or diagonal.
I: positive integer n.
O: all possible ways n queens can be placed on an nxn chessboard so that no two queens threaten each other. Each output consists of an array of integers col indexed from 1 to n, where col[i] is the column where the queen in the ith row is placed.
-------------------------------------------------------------------
void queens(index i)
{ index j;
if(promising(i))
if(i == n) cout << col[1] through col[n];
else
for(j=1;j<=n;j ) {
col[i 1]=j;
queens(i 1);
}
}
-------------------------------------------------------------------
bool promising(index i)
{ index k; bool switch;
k = 1; switch = true;
while(k < i && switch) {
if(col[i] == col[k] || abs(col[i] – col[k]) == i – k)
switch = false;
k ;
}
return switch;
} ~ 勿在浮沙上面築高塔 ~
------
~ 勿在浮沙上面築高塔 ~ |
csf0427
一般會員 ![]() ![]() 發表:6 回覆:8 積分:2 註冊:2004-07-26 發送簡訊給我 |
|
csf0427
一般會員 ![]() ![]() 發表:6 回覆:8 積分:2 註冊:2004-07-26 發送簡訊給我 |
我又想了一下你的問題,你的問題可以做個簡化:
其實只是在找2種最短路徑:
(8,8)→(3,2)→(7,3)→(4,4) 或是
(8,8)→(4,4)→(7,3)→(3,2) 2種
由於騎士的走法是可逆的,
因此(3,2)→(7,3)和(7,3)→(3,2)這2種最短路徑走法是一樣的
同理(4,4)→(7,3)和(7,3)→(4,4)也是一樣的
那麼,最短路徑就決定於(8,8)→(3,2)或(8,8)→(4,4)這二者了
這樣子,只要考慮這4個點中,任2點的最短路徑,有沒有比較簡化一點?
再來,騎士每次可以走的路徑,有8個方向,最笨的方法你可以用搜尋的,
舉例來說,騎士走第一步,座標會有8種變化
x 1,y 2
x 1,y-2 (以下省掉x和y)
2,-1
2, 1
-1,-2
-1, 2
-2, 1
-2,-1
那麼走第2步呢?就是上面8種再走一次,
如走了x 1,y 2後,再走一次,就是x 2,y 4,或是
1, 2→ 1,-2,也就是 2, 0
1, 2→ 2,-1,也就是 3, 1
...
就有8*8=64種了(其實扣除掉走回到前一步的選擇,只有8*7=56種) 第3步最多就是8的3次方
第4步最多就是8的4次方
...
直到走到目標點上,西洋棋不過8*8的空間可走,也就是說,最多8步,一定可以走到,所以用最笨的方法,也不過一千多萬次,就可以解出來了,你可以再加上一些限制,像是不可以走出棋盤、不可以走到曾走過的點,那麼絕對可以很快就解出來的。
以現在電腦的速度,這個複雜度絕對可以負荷得了,而且我想在不到一秒之內,應該就解出來了吧?
希望這樣寫,對你有點幫助。
|
本站聲明 |
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。 2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。 3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇! |