• dfs()


    const int n = 4;
    
    void dfs(int cur)
    {
        if(n==cur)
        {
            for(int i=0;i<n;i++)
            {
                for(int j=0;j<n;j++)
                {
                    if(pos[i]==j)
                    {
                        cout<<'X';
                    }
                    else
                    {
                        cout<<'O';
                    }
                }
                if(i==n-1)
                {
                    cout<<endl;
                }
            }
            cout<<endl;
            couter++;
        }
        else
        {
            for(int i=0;i<n;i++)
            {
                if(!vis[0][i]&&!vis[1][cur+i]&&!vis[2][cur+n-i])//这个数组的作用是起到对应关系,只要这个坐标的行和列,满足cur+i相等,或者cur-i想的相等
                {
                    pos[cur]=i;
                    vis[0][i]=1;
                    vis[1][cur+i]=1;
                    vis[2][cur-i+n]=1;
                    dfs(cur+1);
                    vis[0][i]=0;
                    vis[1][cur+i]=0;
                    vis[2][cur-i+n]=0;
                }
            }
        }
    }
    #include <bits/stdc++.h>
    
    using namespace std;
    
    const int maxn=6;
    const int maxm=6;
    
    int vis[maxm][maxn]={0};
    
    void dfs(int x,int y,int cur)
    {
        if(x<maxn&&x>=0&&y<maxm&&y>=0&&!vis[x][y])
        {
            vis[x][y]=cur;
            if(cur==maxm*maxn)
            {
                for(int i=0;i<maxm;i++)
                {
                    for(int j=0;j<maxn;j++)
                    {
                        cout<<setw(4)<<vis[i][j];
                    }
                    cout<<endl;
                }
                vis[x][y]=0;
                return;
            }
            else
            {
                cur++;
                dfs(x-1,y-2,cur);
                dfs(x-1,y+2,cur);
                dfs(x-2,y-1,cur);
                dfs(x-2,y+2,cur);
                dfs(x+1,y-2,cur);
                dfs(x+1,y+2,cur);
                dfs(x+2,y-1,cur);
                dfs(x+2,y+1,cur);
                vis[x][y]=0;
            }
        }
        else
        {
            return;
        }
    }
    
    int main()
    {
        dfs(0,0,1);
        return 0;
    }
  • 相关阅读:
    Pascal's Triangle II
    Pascal's Triangle
    Path Sum II
    Path Sum
    plusOne
    Divide Two Integers
    64. ZigZag Conversion
    63. Swap Nodes in Pairs && Rotate List && Remove Nth Node From End of List
    62. Divide Two Integers
    61. Unique Paths && Unique Paths II
  • 原文地址:https://www.cnblogs.com/-Asurada-/p/10903269.html
Copyright © 2020-2023  润新知