• DFS模板


    POJ2488

    http://poj.org/problem?id=2488

    注意字典序。

     1  1 #include<iostream>
     2  2 #include<cstdio>
     3  3 #include<cstring>
     4  4 #include<algorithm>
     5  5 using namespace std;
     6  6 int dir[8][2]={-2,-1,-2,1,-1,-2,-1,2,1,-2,1,2,2,-1,2,1};
     7  7 int map[100][100];
     8  8 char a[200];
     9  9 int p,q,flag;
    10 10 int check(int x,int y)                          // 边界条件和约束条件的判断 
    11 11 {
    12 12     if(!map[x][y]&&x<=p&&x>0&&y<=q&&y>0)
    13 13     return 1;
    14 14     return 0;
    15 15 }
    16 16 void dfs(int x,int y,int s)
    17 17 {
    18 18     if(s==p*q&&!flag)                                // 出现目标态G
    19 19     {
    20 20         for(int j=0;j<s*2;j++)
    21 21         printf("%c",a[j]);
    22 22         printf("
    
    ");
    23 23         flag=1;                                    //标记,非常重要。 
    24 24         return;
    25 25     }
    26 26     for(int i=0;i<8&&!flag;i++)
    27 27     {
    28 28         int n=x+dir[i][0];int m=y+dir[i][1];      // 按照规则生成下一个节点,注意必须重新定义变量 
    29 29         if(check(n,m))
    30 30         {
    31 31             map[n][m]=1;
    32 32             a[2*s]='A'+n-1; 
    33 33             a[2*s+1]=m+'0';
    34 34         dfs(n,m,s+1);
    35 35         map[n][m]=0;
    36 36         }
    37 37 }
    38 38 }
    39 39 main()
    40 40 {
    41 41     int t,cas=1;
    42 42     scanf("%d",&t);
    43 43     while(t--)
    44 44     {
    45 45         scanf("%d%d",&q,&p);
    46 46         printf("Scenario #%d:
    ",cas++);
    47 47         memset(map,0,sizeof(map));
    48 48         flag=0;
    49 49         map[1][1]=1;
    50 50         a[0]='A';a[1]='1';
    51 51         dfs(1,1,1);
    52 52         if(!flag)
    53 53         printf("impossible
    
    ");
    54 54     }
    55 55 }
  • 相关阅读:
    Opencv-Python 学习
    Python图片处理
    sae flask 微信公众平台开发
    Python 定位字符串
    Python检测IP合法 是否为公网IP
    Python requests 为pfsense 添加Routes
    lua-nginx-module 学习
    CDN 学习笔记
    教程
    2020-2021-1 20209327 《Linux内核原理与分析》第十二周作业
  • 原文地址:https://www.cnblogs.com/CrazyBaby/p/5714945.html
Copyright © 2020-2023  润新知