UVa 639 - Don't Get Rooked
来源:互联网 发布:网络合同app 编辑:程序博客网 时间:2024/06/08 06:48
/*回溯法*/#include <iostream>#include <cstring>#include <cstdio>#include <cmath>#include <algorithm>using namespace std;const int MAX = 4+2;int board[MAX][MAX]; //棋盘int n; // n*nint most; //输入时判断最大rooksint max_rooks; //最大rooks//判断当前位置是否可以插入int ok(int x, int y){ for(int i=y-1; i>=0; i--) { if(board[x][i] == 2) return 0; if(board[x][i] == 1) break; } for(int i=x-1; i>=0; i--) { if(board[i][y] == 2) return 0; if(board[i][y] == 1) break; } return 1;}//深度遍历,return 1:找到最大值了,直接返回int dfs(int x, int y, int rooks){ if(rooks==most) {max_rooks = rooks; return 1;} if(x==n) { if(rooks > max_rooks) max_rooks = rooks; return 0; } int t_x, t_y; //下一步x、y坐标 if(y<n-1) {t_x = x; t_y = y+1;} else {t_x = x+1; t_y=0;} if(board[x][y] == 0 && ok(x, y)) { board[x][y] = 2; rooks++; if(dfs(t_x, t_y, rooks)) return 1; rooks--; board[x][y] = 0; } if(dfs(t_x, t_y, rooks)) return 1; return 0;}int main(void) { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); #endif while(scanf("%d", &n)==1 && n!=0) { char ch; max_rooks = 0; most = 0; getchar(); for(int i=0; i<n; i++) { int found_dot = 0; for(int j=0; j<n; j++) { ch = getchar(); if(ch == '.') { if(!found_dot) { most++; found_dot = 1; } board[i][j] = 0; } else if(ch=='X') { found_dot = 0; board[i][j] = 1; } } while((ch=getchar()) != '\n'); } dfs(0, 0, 0); printf("%d\n", max_rooks); } return 0;}