#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
using namespace std;
class Solver{
public:
//int x, y;
int biggest_count, n;
bool Safe(int x, int y, vector<vector<char> > Map){
for(int i = x-1; i >= 0; i--){//终止条件一定要包括等号
if(Map[i][y] == 'O')
return false;
if(Map[i][y] == 'X')
break;
}
for(int j = y-1; j >= 0; j--){
if(Map[x][j] == 'O')
return false;
if(Map[x][j] == 'X')
break;
}
return true;
}
void Search(int k, int count, vector<vector<char> >& Map){
if(k == n*n){
if(count > biggest_count)
biggest_count = count;
return;}
else{
int x = k/n;//必须定义在这儿成局部变量
int y = k%n;
if(Map[x][y] == '.' && Safe(x, y, Map)){
Map[x][y] = 'O';
Search(k+1, count+1, Map);//保证回溯回来的时候,xy值还是原来的
Map[x][y] = '.';}
Search(k+1, count, Map);}
}
int StartProcess(int dimension, vector<vector<char> >& Map){
int k = 0;//k, count, Map随着函数的嵌套一直在变化,所以最好作为输入参数,保证同一层回溯回来时是一致的
int count = 0;
biggest_count = 0;//这两个值不会随着嵌套,发生变化
n = dimension;
Search(k, count, Map);
return biggest_count;//return的是类的属性
}
};
int main()
{
int n;
string s;
vector<int> outcome;
vector<vector<char> > Matrix;
Solver solver;
while(cin >> n){
getchar();
if(n == 0)
break;
Matrix.resize(n);
for(int i = 0; i < n; i++){
getline(cin, s);
for(int j =0; j< n; j++){
Matrix[i].push_back(s[j]);
}
}
outcome.push_back(solver.StartProcess(n, Matrix));
Matrix.clear();
}
for(int i = 0; i < outcome.size(); i++){
cout << outcome[i] << endl;
}
return 0;
}
坑:
1、xy要保证在回溯回来后还是原来的,所以必须局部变量!
2、连续解多个问题需要初始化;
3、k, count, map都元素随着嵌套在变化,为了保证回溯后的一致,最好作为输入参数使用,不能作为class的属性;
4、浙大的编译器,vector<vector<int> >需要有个空格,getchar()需要#include<stdio.h>;