n queen 問題

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

(Python 程式碼)

#影片 6:40 mins 處


def place(t): #這⼀列(第 x[t] 層)放入的位置是否正確
for i in range(1, t):#判斷這個點是否在前⼀個點的斜線路徑上
if t - i == abs(x[t] - x[i]): #若斜率為 +1 或 -1(abs 為絕對值)
return False #還原⾄上⼀步,再次嘗試
return True

#影片 9:00 mins 處


def dfs(t):
global ans
if t > N: #印出盤⾯
ans += 1 #答案數加⼀
for i in range(1, N + 1):
for j in range(1, N + 1):
print('Q' if j == x[i] else 'x', end='\n' if j == N else '') #如果 j == x[I] 印 ’Q’,否則印
’x’ ;如果 j == N 換⾏,否則列印後不換⾏
print('')
else: #重新判斷
for i in range(t, N + 1):
x[t], x[i] = x[i], x[t] # 1,2,3,.... 變成 2,1,3,......
if place(t): dfs(t + 1) # 若 place(t) 為真,執⾏ dfs(t + 1)
x[t], x[i] = x[i], x[t] # 2,1,3,...... 變成 1,2,3,…. ???

N = int(input("輸入 N :")) #輸入決定 N 為多少


x = [i for i in range(N + 1)] # 設立 x[i] 陣列?
ans = 0 #答案數初始為 0
dfs(1) #從第⼀列開始判斷
print(ans)

*兩程式間的差異:

Python 可以寫成 x[t], x[i] = x[i], x[t]


但是 C 要在建立⼀個 swap 函式才能互換

(C 程式碼)
#include <stdio.h>
#include <stdlib.h>

int x[12 + 1];


int ans = 0, N;
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
int place(int t) {
for (int i = 1; i < t; i++)
if (t - i == abs(x[t] - x[I])) #若斜率為 +1 或 -1(abs 為絕對值)
return 0;
return 1;
}
void dfs(int t) {
if (t > N) {
ans++;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++)
printf("%c", j == x[i] ? 'Q':'x');
printf("\n");
}
printf("\n");
}
else {
for (int i = t; i <= N; i++) {
swap(&x[t], &x[i]);
if (place(t)) dfs(t + 1);
swap(&x[t], &x[i]);
}
}
}
int main() {
scanf("%d", &N);
ans = 0;
for (int i = 1; i <= N; i++) x[i] = i;
dfs(1);
printf("%d\n", ans);
return 0;
}

You might also like