ZOJ1002

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=2

DFS。对于每一个方格都有放或不放两种选择(该方格合法),枚举每一个方格,分放和不放两个方向的搜索。

对于优化问题,就从上一层搜索停下的哪一行开始,没有必要每次都从第一行第一个方格开始。

#include<iostream>
using namespace std;

char city[4][4];
int ans;
int n;

bool OK(int x, int y)
{
    if (x>=n || y>=n)
        return false;
    if (city[x][y] == 'X')
        return false;
    int xx = x, yy = y;
    while (xx < n && city[xx][y] != 'X')
    {
        if (city[xx][y] == '*')
            return false;
        xx++;
    }
    xx = x;
    while (xx >= 0 && city[xx][y] != 'X')
    {
        if (city[xx][y] == '*')
            return false;
        xx--;
    }

    while (yy < n && city[x][yy] != 'X')
    {
        if (city[x][yy] == '*')
            return false;
        yy++;
    }
    yy = y;
    while (yy >= 0 && city[x][yy] != 'X')
    {
        if (city[x][yy] == '*')
            return false;
        yy--;
    }

    return true;
}

void DFS(int x,int now)  //x表示上一层停下的那一行,now表示当前已经有了多少个碉堡
{
    ans = now > ans ? now : ans;

    for (int i=x; i<n; i++)
        for (int j=0; j<n; j++)
            if (OK(i,j))  //判断方格的合法性
    {
        city[i][j] = '*';
        DFS(i,now+1);
        city[i][j] = '.';
    }
}

int main()
{
    while (cin>>n && n)
    {
        for (int i=0; i<n; i++)
            for (int j=0; j<n; j++) cin>>city[i][j];
        ans = 0;
        DFS(0,0);
        cout<<ans<<endl;
    }

    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值