题意:输入一个n*m棋盘(n,m<10),某些格子有标记。用最少的皇后守卫(即占据或者攻击)所有带标记的格子。
#pragma comment(linker, "/STACK:102400000, 102400000") #include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<stack> #include<deque> #include<queue> #include<list> #define Min(a, b) ((a < b) ? a : b) #define Max(a, b) ((a < b) ? b : a) typedef long long ll; typedef unsigned long long llu; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const ll LL_INF = 0x3f3f3f3f3f3f3f3f; const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const int MOD = 1e9 + 7; const double pi = acos(-1.0); const double eps = 1e-8; const int MAXN = 10000 + 10; const int MAXT = 10000 + 10; using namespace std; char a[15][15]; int vis[5][30]; int mark[15][15]; int kase; int n, m; bool judge(){ for(int i = 0; i < n; ++i){//判断所有被标记的正方形是否被保护 for(int j = 0; j < m; ++j){ if(mark[i][j] && !vis[0][i] && !vis[1][j] && !vis[2][j + i] && !vis[3][j - i + n]) return false; } } return true; } bool dfs(int cur, int pos, int tot){ if(cur == tot){ if(judge()){ printf("Case %d: %d\n", kase, tot); return true; } return false; } else{ for(int i = pos; i < n * m; ++i){ int x = i / m; int y = i % m; int tmp1 = vis[0][x]; int tmp2 = vis[1][y]; int tmp3 = vis[2][x + y]; int tmp4 = vis[3][y - x + n]; vis[0][x] = vis[1][y] = vis[2][x + y] = vis[3][y - x + n] = 1; if(dfs(cur + 1, pos, tot)) return true; vis[0][x] = tmp1; vis[1][y] = tmp2; vis[2][x + y] = tmp3; vis[3][y - x + n] = tmp4; } } return false; } int main(){ while(scanf("%d", &n) == 1){ if(!n) return 0; ++kase; scanf("%d", &m); memset(a, 0, sizeof a); memset(mark, 0, sizeof mark); for(int i = 0; i < n; ++i){ scanf("%s", a[i]); } for(int i = 0; i < n; ++i){ for(int j = 0; j < m; ++j){ if(a[i][j] == ‘X‘){ mark[i][j] = 1; } } } for(int i = 0; ; ++i){ memset(vis, 0, sizeof vis); if(dfs(0, 0, i)) break; } } return 0; }
UVA - 11214 Guarding the Chessboard(守卫棋盘)(迭代加深搜索)
原文:http://www.cnblogs.com/tyty-Somnuspoppy/p/6308598.html