生活随笔
收集整理的這篇文章主要介紹了
[蓝桥杯][基础练习VIP]2n皇后问题(深搜)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
輸出一個整數(shù),表示總共有多少種放法。
樣例輸入
4
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
樣例輸出
2
思路:數(shù)據(jù)量不大,就是暴力搜索,先安排一種皇后,然后再安排另一種皇后。注意判斷的條件。
代碼如下:
#include<bits/stdc++.h>
#define ll long long
using namespace std
;const int maxx
=10;
int a
[maxx
][maxx
];
int vis
[maxx
][maxx
];
int n
;inline int check(int x
,int y
,int k
)
{for(int i
=1;i
<=n
;i
++) if(vis
[i
][y
]==k
&&i
!=x
) return 0;for(int i
=1;i
<=n
;i
++) if(vis
[x
][i
]==k
&&i
!=y
) return 0;for(int i
=1;i
<x
;i
++)for(int j
=1;j
<=n
;j
++) if(vis
[i
][j
]==k
&&abs(i
-x
)==abs(j
-y
)) return 0;return 1;
}
inline void Dfs(int x
,int &ans
)
{if(x
==n
+1){ans
++;return ;}for(int i
=1;i
<=n
;i
++){if(a
[x
][i
]&&vis
[x
][i
]==0&&check(x
,i
,2)){vis
[x
][i
]=2;Dfs(x
+1,ans
);vis
[x
][i
]=0;}}
}
inline void dfs(int x
,int &ans
)
{if(x
==n
+1){Dfs(1,ans
);return ;}for(int i
=1;i
<=n
;i
++){if(a
[x
][i
]&&vis
[x
][i
]==0&&check(x
,i
,1)){vis
[x
][i
]=1;dfs(x
+1,ans
);vis
[x
][i
]=0;}}
}
int main()
{scanf("%d",&n
);for(int i
=1;i
<=n
;i
++)for(int j
=1;j
<=n
;j
++) scanf("%d",&a
[i
][j
]);int ans
=0;dfs(1,ans
);cout
<<ans
<<endl
;return 0;
}
努力加油a啊,(o)/~
總結(jié)
以上是生活随笔為你收集整理的[蓝桥杯][基础练习VIP]2n皇后问题(深搜)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。