HDU1045 Fire Net【DFS】

Title link: HDU1045 Fire Net【DFS】

Question: A chessboard with a size of at most 4*4. There are some walls on the chessboard to block bullets. The turret can fire bullets in four directions. Ask how many turrets can be placed if they can not attack each other;

Analysis: the search is right;

#include<bits/stdc++.h>
using namespace std;
char mp[5][5];
int n,ans;
bool check(int x,int y)
{
    for(int i=y;i>=0;i--) 
    {
        if(mp[x][i]=='*') return 0;
        if(mp[x][i]=='X') break;
    }
    for(int i=x;i>=0;i--)
    {
        if(mp[i][y]=='*') return 0;
        if(mp[i][y]=='X') break;
    }
    return 1;
}
void dfs(int pos,int num)
{
    if(pos==n*n) {ans=max(ans,num);return;}
    int x=pos/n,y=pos%n;
    if(mp[x][y]=='.' && check(x,y))
    {
        mp[x][y]='*';
        dfs(pos+1,num+1);
        mp[x][y]='.';
    }
    dfs(pos+1,num);
}
void rua()
{
    ans=0;
    for(int i=0;i<n;i++) scanf("%s",mp[i]);
    dfs(0,0);
    printf("%d\n",ans);
}
int main()
{
    while(~scanf("%d",&n) && n) rua();
    return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_43813163/article/details/102823460