1.29-寒假集训-5【深度优先搜索】

· · 个人记录

深度优先搜索(DFS)

-P2105 K皇后-

思路

本题实现参照八皇后

## [-T726810 搜索进阶1.29-](https://www.luogu.com.cn/problem/T726810?contestId=306336)
### 思路
- 首先将所有的非数字提前存储起来,然后进行一维 $DFS$ 并考虑每个点填的数字是否会影响行,列和对角线
### Code
```cpp
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=10+10;
struct node
{
    int x,y;
}path[N*N];
int n,cnt=0,ans=0;
char c[N][N];
bool check(int x,int y,char k)
{
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            if(i==x && c[i][j]==k)
            {
                return false;
            }
            if(j==y && c[i][j]==k)
            { 
                return false;
            }
            if(i-j==x-y && c[i][j]==k)
            {
                return false;
            }
            if(i+j==x+y && c[i][j]==k)
            {
                return false;
            }
        }
    }
    return true;
}
void dfs(int cur)
{
    if(cur==cnt+1)
    {
        ans++;
        return;
    }
    for(int i=1;i<=n;i++)
    {
        if(check(path[cur].x,path[cur].y,i+'0'))
        {
            c[path[cur].x][path[cur].y]=i+'0';
            dfs(cur+1);
            c[path[cur].x][path[cur].y]='*';
        }
    }
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            cin>>c[i][j];
            if(c[i][j]=='*')
            {
                path[++cnt]={i,j};
            }
        }
    }
    dfs(1);
    cout<<ans;
    return 0;
}

-P1219 [USACO1.5] 八皇后 Checker Challenge-

思路