这道题暴力秒过,以前在ZOJ上见过,当时不会,还以为不剪枝铁定超呢,结果纯暴力就过了。
# include <cstdio> # include <cstring> # define N 4 + 3 int n, ans; char g[N][N]; bool check(int x, int y) { int i = x; if (g[x][y] != '.') return false; while (i <= n) { if (g[i][y] == 'X') break; else if (g[i][y] == (i-1)*n+y) return false; else ++i; } i = x-1; while (i >= 1) { if (g[i][y] == 'X') break; else if (g[i][y] == (i-1)*n+y) return false; else --i; } i = y; while (i <= n) { if (g[x][i] == 'X') break; else if (g[x][i] == (x-1)*n+i) return false; else ++i; } i = y-1; while (i >= 1) { if (g[x][i] == 'X') break; else if (g[x][i] == (x-1)*n+i) return false; else --i; } return true; } void dfs(int x, int y, int cnt) { int i = 1, j = 1; //int tmp = (x-1)*n + y + 1, i = (tmp-1)/n+1, j = (tmp-1)%n+1; // 错误的剪枝,没有通过样例 //if (tmp == n*n) ans = (cnt > ans ? cnt : ans); if (cnt > ans) ans = cnt; for ( i = 1; i <= n; ++i) for ( j = 1; j <= n; ++j) { if (check(i,j)) { g[i][j] = (i-1)*n+j; dfs(i, j, cnt+1); g[i][j] = '.'; } } } void init(void) { for (int i = 1; i <= n; ++i) scanf("%s", g[i]+1); } void solve(void) { ans = 0; for (int i = 1; i <= n; ++i) for (int j = 1; j <= n; ++j) { if (g[i][j]=='.') { g[i][j] = (i-1)*n+j; dfs(i, j, 1); g[i][j] = '.'; } } printf("%d\n", ans); } int main() { while (scanf("%d", &n), n) { init(); solve(); } return 0; }
/**/