ZOJ-1002 回溯
1. 题目描述: 类似于八皇后问题,不同之处是斜线可以放,同时加了wall,以阻止bullet的穿透
2. 算法思想:回溯法,从第一位置开始,判断其是否满足约束条件,如果满足则放置blockhouse;如果不满足,则回溯下一个位置。
3. 算法代码:
3.1 举例:
以4*4地图为例,放置有3个Wall,
3.2 算法代码
View Code
#include <iostream>
using namespace std;
const int N=4; //map size
char m[N][N]; //map definition
int totalNum=0; //the max blockhouses can be put
bool IsOk(int r,int c) //check whether the blockhouse can be put or not
{
int i;
//check whether bullet has been set at the same row or not
for(i=c-1;i>=0;--i)
{
if(m[r][i] == 'O') //blockhouse has been set at the same row
return false;
if(m[r][i] == 'X') //wall has been set,so blockhouse can be put
break;
}
//check whether bullet has been set at the same col or not
for(i=r-1;i>=0;--i)
{
if(m[i][c] == 'O') //blockhouse has been set at the same col
return false;
if(m[i][c] == 'X') //wall has been set,so blockhouse can be put
break;
}
return true;
}
//back track for all the city,find out all possible number of blockhouses which can be set
void BackTrack(int k, int cnt,int n)
{
int row,col;
if(k==n*n )
{
if(cnt>totalNum) //arrive the end
{
totalNum=cnt; //get the final number of blockhouses
return;
}
}
else
{
row = k/n; //row number
col = k%n; //col number
if(m[row][col]=='.' && IsOk(row,col)) //blockhouse can be set
{
m[row][col] = 'O'; //change its status
BackTrack(k+1,cnt+1,n); //backtrack next block,
m[row][col] = '.';
}
BackTrack(k+1,cnt,n);
}
}
int main()
{
int dn;
while(cin>>dn && dn)
{
int i,j;
for(i=0;i!=dn;++i)
for(j=0;j!=dn;++j)
cin>>m[i][j];
totalNum=0;
BackTrack(0,0,dn);
cout<<totalNum<<endl;
}
return 0;
}
作者:ballwql
本文为作者原创,版权所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。