《Cracking the Coding Interview》——第9章:递归和动态规划——题目9

2014-03-20 04:08

题目:八皇后问题。

解法:DFS解决。

代码:

 1 // 9.9 Eight-Queen Problem, need I say more?

 2 #include <cstdio>

 3 #include <vector>

 4 using namespace std;

 5 

 6 class Solution

 7 {

 8 public:

 9     void eigthQueens(int n, vector<vector<int> > &result) {

10         if (n < 1) {

11             return;

12         }

13         

14         vector<int> v;

15         dfs(0, n, v, result);

16         v.clear();

17     }

18 private:

19     void dfs(int idx, int n, vector<int> &v, vector<vector<int> > &result) {

20         if (idx == n) {

21             result.push_back(v);

22             return;

23         }

24 

25         int i, j;

26         for (i = 0; i < n; ++i) {

27             for (j = 0; j < idx; ++j) {

28                 if (v[j] == i || myabs(idx - j) == myabs(i - v[j])) {

29                     // conflict

30                     break;

31                 }

32             }

33             if (j == idx) {

34                 v.push_back(i);

35                 dfs(idx + 1, n, v, result);

36                 v.pop_back();

37             }

38         }

39     }

40     

41     int myabs(int n) {    

42         return (n >= 0 ? n : -n);

43     }

44 };

45 

46 int main()

47 {

48     vector<vector<int> > result;

49     Solution sol;

50     int n;

51     int i, j, k;

52     

53     while (scanf("%d", &n) == 1 && n > 0) {

54         sol.eigthQueens(n, result);

55         for (k = 0; k < (int)result.size(); ++k) {

56             for (i = 0; i < n; ++i) {

57                 for (j = 0; j < result[k][i]; ++j) {

58                     putchar('0');

59                 }

60                 putchar('1');

61                 for (j = result[k][i] + 1; j < n; ++j) {

62                     putchar('0');

63                 }

64                 putchar('\n');

65             }

66             putchar('\n');

67         }

68         printf("%d\n", (int)result.size());

69         for (i = 0; i < (int)result.size(); ++i) {

70             result[i].clear();

71         }

72         result.clear();

73     }

74     

75     return 0;

76 }

 

你可能感兴趣的:(interview)