N-Queen 문제 소스코드: Difference between revisions
From IT Wiki
(새 문서: == C 언어 == <syntaxhighlight lang='c' line='line'> #include <stdio.h> #include <stdlib.h> void queens(int); int promising(int); int n; int col[255]={0,}; FILE *inputFile, *outp...) |
No edit summary |
||
Line 52: | Line 52: | ||
== 출처 == | == 출처 == | ||
[http://raisonde.tistory.com/entry/C언어-소스-Backtracking을-이용한-N-Queen-문제-해결법 지식잡식 블로그] | [http://raisonde.tistory.com/entry/C언어-소스-Backtracking을-이용한-N-Queen-문제-해결법 지식잡식 블로그] | ||
[[분류:알고리즘]] |
Latest revision as of 13:04, 6 May 2018
C 언어[edit | edit source]
#include <stdio.h>
#include <stdlib.h>
void queens(int);
int promising(int);
int n;
int col[255]={0,};
FILE *inputFile, *outputFile;
int main() {
char fileName[255];
printf("input num? ");
scanf("%d", &n);
queens(0);
}
void printResult() {
int i;
printf("result : ");
for(i = 1; i<=n; i++) printf("%d ", col[i]);
exit(1);
}
void queens(int i) {
int j;
if(promising(i)) {
if(i == n) printResult();
else
for(j = 1; j <= n; j++) {
col[i+1] = j;
queens(i+1);
}
}
}
int promising(int i) { // 직선, 대각선으로 만나는지 검사
int k = 1, promising = 1;
while(k < i && promising) {
if(col[i] == col[k] || abs(col[i]-col[k]) == abs(i-k))
promising = 0;
k++;
}
return promising;
}