DFS题目总结

ZOJ 1002 Fire Net



AC代码:

#include<iostream>
using namespace std;
int n;
int ans;
char map[10][10];
bool check(int x,int y);
void dfs(int point,int sum);
int main()
{
    while(scanf("%d",&n)!= EOF)
    {
        if(n==0)
            break;
        getchar();
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<n;j++)
                scanf("%c",&map[i][j]);
            getchar();
        }
        ans = 0;
        dfs(0,0);
        printf("%d\n",ans);
    }
    return 0;
}
bool check(int x,int y)
{
    bool flag = true;
    for(int i=x;i>=0;i--)
    {
        if(map[i][y]=='X')
            break;
        else if(map[i][y]=='b')
        {
            flag = false;
            break;
        }
    }
    for(int i=y;i>=0;i--)
    {
        if(map[x][i]=='X')
            break;
        else if(map[x][i]=='b')
        {
            flag = false;
            break;
        }
    }
    return flag;
}
void dfs(int point,int sum)
{
    if(point == n*n)
    {
        if(sum>ans)
            ans = sum;
        return;
    }
    int x = point/n;
    int y = point%n;
    if(map[x][y]=='.'&&check(x,y))
    {
        map[x][y]='b';
        dfs(point+1,sum+1);
        map[x][y]='.';
    }
        dfs(point+1,sum);
}

HDU 1016 Prime Ring Problem



AC代码:

#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
int n;
vector<vector<int>> res;
vector<int> nums;
bool visit[30];
bool sumPrime(int x);
void DFS();
void dfs(vector<int> path);
int main()
{
    int i=0;
    fill(visit,visit+n,false);
    while(scanf("%d",&n)!=EOF)
    {
        i++;
        res.clear();
        DFS();
        printf("Case %d:\n",i);
        for(int i=0;i<res.size();i++)
        {
            for(int j=0;j<n;j++)
            {
                printf("%d",res[i][j]);
                if(j!=n-1)
                    printf(" ");
            }
            printf("\n");
        }
        printf("\n");
    }
    return 0;
}
bool sumPrime(int x)
{
    for(int i=2;i<=sqrt(x);i++)
        if(x%i==0)
            return false;
    return true;
}
void DFS()
{
    vector<int> path;
    path.push_back(1);
    dfs(path);
    return;
}
void dfs(vector<int> path)
{
    if(path.size()==n)
    {
        if(sumPrime(path[n-1]+1))
            res.push_back(path);
        return;
    }
    for(int j=2;j<=n;j++)
    {
        if(visit[j]==false&&sumPrime(path[path.size()-1]+j))
        {
            path.push_back(j);
            visit[j]=true;
            dfs(path);
            path.pop_back();
            visit[j]=false;
        }
    }
    return;
}
posted @ 2020-04-11 12:10  Cutey_Thyme  阅读(275)  评论(0编辑  收藏  举报