639

简单回溯,但对我来说不算很简单,毕竟我的搜索底子很浅,还好这道做的还不错,调了一小会,发现是到边界的时候没return,加上之后就过了。

思路很简单,只要把所有的情况都找出来加以判断就行了,dfs实现

//============================================================================
// Name        : 639.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <cstdio>
using namespace std;


char s[10][10];
int a[10][10];
int n, Max;

int judge(){
	int t;
	for(int i = 0;i < n;i++){
		t = 0;
		for(int j = 0;j < n;j++){
			if(a[i][j] == -1){
				t = 0;
			}
			else if(a[i][j] == 1){
				t++;
			}
			if(t > 1) return 0;
		}
		t = 0;
		for(int j = 0;j < n;j++){
			if(a[j][i] == -1){
				t = 0;
			}
			else if(a[j][i] == 1){
				t++;
			}
			if(t > 1) return 0;
		}
	}
	return 1;
}

int NUM(){
	int t = 0;
	for(int i = 0;i < n;i++){
		for(int j = 0;j < n;j++){
			if(a[i][j] == 1) t++;
		}
	}
	return t;
}


void dfs(int i, int j){
	if(i == n){
		if(judge() == 1){
			if(Max < NUM()){
				Max = NUM();
			}
		}
		return;
	}
	if(s[i][j] == 'X'){
		a[i][j] = -1;
		if(j == n-1) dfs(i+1, 0);
		else dfs(i, j+1);
	}
	else{
		a[i][j] = 0;
		if(j == n-1) dfs(i+1, 0);
		else dfs(i, j+1);
		a[i][j] = 1;
		if(j == n-1) dfs(i+1, 0);
		else dfs(i, j+1);
	}
}


int main() {
	freopen("a.txt", "r", stdin);
	while(scanf("%d", &n)&&n){
		Max = 0;
		for(int i = 0;i < n;i++){
			scanf("%s", s[i]);
		}
		dfs(0,0);
		printf("%d\n", Max);
	}
	return 0;
}

posted @ 2011-05-25 23:33  KOKO's  阅读(145)  评论(0编辑  收藏  举报