Indeed-tokyo笔试题三:
级别:难
题目:6*6的矩阵,每个元素为o或者.
给出一个矩阵,使得每行每列o的个数都为3
求出所有可能的放置方式数目。
思路:每列求出当前转态合法放置数,按行进行深度搜索
#include <iostream>
#include<vector>
using namespace std;
#include <time.h>
#include <sys/timeb.h>
//程序计时
int get_time(string r)
{
struct timeb rawtime;
ftime(&rawtime);
static int ms = rawtime.millitm;
static unsigned long s = rawtime.time;
int out_ms = rawtime.millitm - ms;
unsigned long out_s = rawtime.time - s;
if (out_ms < 0)
{
out_ms += 1000;
out_s -= 1;
}
ms = rawtime.millitm;
s = rawtime.time;
int total = 1000*out_s+out_ms;
cout<<r<<": "<<total<<"ms"<<endl;
return total;
}
//行是否已经成功,恰为3个
bool rowSucceed(const vector<vector<char>> &m,int row){
int rn=0,cn=0;
for(int i=0;i<6;++i)
if(m[row][i]=='o')rn++;
if(rn==3)return true;
else return false;
}
//行是否合法
bool rowLegal(const vector<vector<char>> &m,int row){
int rn=0;
for(int i=0;i<6;++i)
if(m[row][i]=='o')rn++;
if(rn<=3)return true;
else return false;
}
//放置了i,j,第j列是否合法
bool colLegal(const vector<vector<char>> &m,int col){
int cn=0;
for(int i=0;i<6;++i)
if(m[i][col]=='o')cn++;
if(cn<=3)return true;
else return false;
}
//在一行里以元素为单位进行深搜出可行的行放置元素排列
void numLegalRow(vector<vector<char>> &m,int r,int c,vector<vector<char>> &res){
if(rowSucceed(m,r)){
res.push_back(m[r]);
}
else{
if(!rowLegal(m,r))return;
for(int j=c;j<6;++j){
if(m[r][j]=='.'){
m[r][j]='o';
if(colLegal(m,j))numLegalRow(m,r,j+1,res);
m[r][j]='.';
}
}
}
}
//按行为单位深度搜索,每次从该行的一个可行节点出发
void numLegalTable(vector<vector<char>> m,int row,int &res){
vector<vector<char>> vtmp;
numLegalRow(m,row,0,vtmp);
//cout<<vtmp.size()<<endl;
if(row==5){
res=res+vtmp.size();
}
else {
for(int p=0;p<vtmp.size();++p){
m[row] = vtmp[p];
numLegalTable(m,row+1,res);
}
}
}
int main()
{
vector<vector<char> > matrix;
for(int i=0;i<6;++i)matrix.push_back(vector<char>(6));
for(int i=0;i<6;++i)
for(int j=0;j<6;++j){
char ch;
cin>>ch;
matrix[i][j]=ch;
}
get_time("begin:");
int res=0;
numLegalTable(matrix,0,res);
cout<<res<<endl;
get_time("end:");
return 0;
}