Depth-first search template examples +

dfs board

bool check(参数) {
  if(满足条件)
    return ture;
  return false;
}
void dfs(int step) {
  if(到达边界){
    输出或其他相关操作 //根据题意添加
    return ;
  }
  if(越界 / 不合法的状态)
    return;
for() {
  if(满足check) {
  修改操作; //根据题意判断是否执行该操作 **1**
  标记;
  dfs(step + 1);//继续下一步
  (还原标记) //根据题意判断是否执行该操作 **2**
                         //如果加上(还原标记)就是 回溯法 
  }
 }
}

1 Number of selected examples

Description Title
known n integers x_1, x_2, x_n, and an integer k (k <n). Optionally adding integers k from n integers in a range of available respectively. For example, when n = 4, k = 3,4 is 3,7,12,193,7,12,19 are integers, all combinations are available and they are as follows:

3+7+12=22

3+7+19=29

7+12+19=38

3+12+19=34

Now, we ask you to calculate the total number of species and is a prime number.

For example the embodiment, only one, and is a prime number: 3 + 7 + 19 + 7 + 19 = 293 = 29.

Sample Input Output
Input
. 4. 3
. 3 12 is. 7. 19
Output
1

#include<iostream>
#include<cstring>
int a[22], p[22];
bool vis[22];
int n, k,sum,ans;
using namespace std;
bool isprime(int n) { //判断素数
        if(n <= 1)  return false;
        for(int i = 2; i  * i  <= n; ++i) 
           if(n % i == 0) 
               return false;
            return true;
}
void dfs(int step){
        if(step == k + 1){
          if(isprime(sum))
            ans++;
            return ;//返回之前的一步(最近一次调用dfs函数的地方)
        }
        for(int i = 1; i <= n; ++i) {
           if(vis[i] == false && i  > p[step - 1]) {
              p[step] = i;
              sum += a[i];
              dfs(step + 1);
              vis[i] = false;
              sum -= a[i];
           }
        }
}
int main() {
     memset(vis,0,sizeof(vis));//初始化
     cin>>n>>k;
     for(int i = 1; i <= n; ++i) {
       cin>>a[i];
       p[i] = i;
     }
     ans = 0;
     dfs(1);
     cout<<ans<<endl;
     return 0; 
}

2 examples maze

Title BACKGROUND
Given an N * M squares maze, T-maze at the barrier, not through the barrier. Given the start point and end point, Q: After a maximum of 1 per box, how many from the start point to the end point coordinate coordinates the program. In the maze to move up and down about four ways, you can only move one square. No obstacles to ensure data starting point.

Title Description
No

Input format
of the first row N, M and T, N row, M being a column, T is the total number of disorders. The second line starting coordinates SX, SY, ending coordinate FX, FY. Then the coordinates of the point T lines, each behavioral disorders.

Output format
given the start point and end point, and asked after each square up to 1 times the total number of programs from the starting point to the end point coordinate coordinates.

Sample Input Output
Input
2 1 2
1 2 1 2
1 2
Output
1
Description / Tips
[data size]

1 ≤ N, m≤5
PS: The picture came out to derive more convenient, it can also be used to do a wide search

#include<iostream>
int a[6][6], book[6][6];
int n, m, t, p, q, sum;
using namespace std;
void dfs(int x, int y, int step) {
   int next[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};
   int tx, ty;
   if(x == p && y == q) { //判断是否到达终点
      sum++; //到达终点,方案数加一
      return ;
   }
   for(int i = 0; i < 3; ++i){
      tx = x + next[i][0];
      ty = y + next[i][1];//计算下一个点的坐标
      if(tx < 1 || tx > n || ty < 1 || ty > m)  continue; //判断是否越界
      if(a[tx][ty] == 0 && book[tx][ty] == 0) {
        book[tx][ty] = 1; //标记
        dfs(tx, ty, step); //尝试下一个点
        book[tx][ty] = 0;//取消标记
      } 
   }
    return;
}
int main(void){
    int sx, sy, fx, fy;
    cin>>n>>m>>t;
    cin>>sx>>sy>>p>>q;
    book[sx][sy]  = 1; //标记该点已走,防止重复走
    for(int i = 1; i <= t; ++i){
       cin>>fx>>fy;
       a[fx][fy] = 1; //障碍物的初始化
    }
    dfs(sx, sy, 0);// 参数一起点横坐标。二 起点纵坐标,三 初始化步数为0
    cout<<sum<<endl; 
    return 0;
}

3 oil field examples

Italian translation of the title
[title] effect matrix input multiple m rows and n columns, with 00 indicating the end of input. Find out how many blocks the oil region, with "@" represents the oil, if two "@" in the horizontal, vertical or diagonal adjacent, say they are in the same area, for each input, output a number expressed several oil region.

Thanks to the translation provided by @songhn

Sample input and output
Input # 1 replication
11

35
# @ # @ #
## @ ##
# # @ # @
18
@@ @ #### #
55
#### @
# @@ # @
# @ @ ##
@ @ @ @ #
@ @ ## @
00
output # 1 copy
0
1
2
2
PS due to restrictions blog format here to change the input symbol sample of
Click here to enter the original title

#include<iostream>
#include<cstring>
char a[103][103];
int n ,m;
using namespace std;
bool check(int x, int y) {
   if(x >= 0 && x <= m && y >= 0 && a[x][y] == '@') //判断是否是油田
      return 1;
   return 0;
}
int dfs(int x, int y){
   int next[8][2] = {{1, 0},{0,1},{-1,0},{0,-1},{1,-1},{-1,1},{-1,-1},{1,1}};
   int tx, ty;
   if(check(x, y)) {
     a[x][y] = '.';
     for(int i = 0; i < 8; ++i) {
       tx = x + next[i][0];
       ty = y + next[i][1];
       dfs(tx, ty);
     }
    return 1;
    }
    return 0;
}
int main() {
   while(cin>>m>>n && (m != 0 && n != 0)) { // 简单粗暴地判断终止输入的条件
     int sum = 0; //切记在循环内部初始化 
     memset(a, 0, sizeof(a));
     for(int i = 0; i < m; ++i){
       cin>>a[i];
     }
     for(int i = 0; i  < m; ++i) {
          for(int j = 0; j  < n; ++j) {
             if(dfs(i, j)) sum++;//发现油田 
          }
       }
      cout<<sum<<endl;
   }
   return 0;
 }

Thanks to predecessors

Released two original articles · won praise 0 · Views 42

Guess you like

Origin blog.csdn.net/qq_45886817/article/details/103963741