sdut1882n皇后问题

http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=1882

搜索 递归回溯

View Code
 1 #include <stdio.h>

 2 #include <stdlib.h>

 3 #include<math.h>

 4 int q[21][21],flag,a[21],f = 0;

 5 void dfs(int i, int n)

 6 {

 7     int j,k,p,l,m;

 8     if(f == 1)

 9     return ;

10     if(i>n)

11     {

12        for(l = 1 ; l <= n ; l++)

13         {

14             printf("%d ", a[l]);

15         }

16         printf("\n");

17         f = 1;

18     }

19     else

20     {

21         for(j = 1 ; j <= n; j++)

22         {

23             flag = 0;

24             for(k = 1 ; k < i ; k++)

25             if(a[k] == j||(abs(k-i)==abs(a[k]-j)))

26             flag = 1;

27             if(flag == 0)

28             {

29                 q[i][j] = 0;

30                 a[i] = j;

31                 dfs(i+1,n);

32                 q[i][j] = 1;

33             }

34         }

35     }

36 }

37 int main()

38 {

39     int n, i, j,p = 1,l;

40     scanf("%d", &n);

41     for(i = 1 ; i <= n ; i++)

42     for(j = 1 ; j <= n ; j++)

43     q[i][j] = 1;

44     dfs(1, n);

45     return 0;

46 }

 

你可能感兴趣的:(问题)