Depth-first search (DFS) and depth-first search for dfs

Source: Internet
Author: User

Depth-first search (DFS) and depth-first search for dfs

Today, I reviewed the deep search of images for priority. I deeply felt that deep search is a plug-in, rather than a plug-in. It is simply a plug-in. dynamic planning cannot be done, and deep search is available, the greedy and greedy deep searches are made, and the collection and Topology Sorting cannot be done. The deep searches are all made. Unfortunately, the deep searches were not very studious in the past.

Depth-First-Search is a Search algorithm. It is the node that traverses the tree along the tree in depth, and the branch of the search tree is as deep as possible. When all the edges of node v have been explored, the search will trace back to the Start Node of the edge of node v. This process continues until all nodes that can be reached from the source node are found. If no node is found, select one of the nodes as the source node and repeat the above process until all nodes are accessed. It is a blind search.


In fact, deep priority Search is a graph algorithm. It is short for DFS, that is, Depth First Search. the process is simply to say that every possible branch path cannot be further penetrated, and each node can only be accessed once.

Deep Search is mainly a process of backtracking, marking that the current vertex has been used. Based on the used vertex, we proceed to the next step. When we finally find that this vertex is unavailable, therefore, the time complexity of the algorithm is (O (n !)); It is easy to cause timeout, but in some cases, it is quite fast to blindly search and traverse all over again, basically all of which are 0 ms. This algorithm and code are easy to write and think about, no wonder that the two gods of dfs won the Turing Award, which is actually 6;

There are many questions on oj that are suitable for Deep Search, such as hdoj1045, the most typical n queen problem, hdoj1258, Nanyang 32 combination number problem, and Nanyang oj58 minimum step number problem, hdoj1016 prime ring problem, poj2loud, zoj1003... (because there are too many questions, only the classic ones are listed );

A few classic search questions and code are provided:

Combination number problem:

Description
Find all the combinations of r (0 <r <= n) numbers from natural numbers 1, 2,..., n (0 <n <10.
Input
Enter n and r.
Output
Output all combinations in a specific order.
Specific order: Values in each combination are arranged in ascending order and in reverse Lexicographic Order.
Sample Input
5 3
Sample output
543542541532531521432431421321

Code:

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;int n,m,vis[1000],a[1000]={1000};void dfs(int step){int i;if(step==n+1){for(i=1;i<n;i++)printf("%d",a[i]);printf("%d\n",a[i]);}for(i=m;i>=1;--i){if(!vis[i]&&i<a[step-1]){vis[i]=1;a[step]=i;dfs(step+1);vis[i]=0;}}}int main(){while(scanf("%d%d",&m,&n),m+n){memset(vis,0,sizeof(vis));dfs(1);}return 0;}

Hangdian 1258:

Problem DescriptionGiven a specified total t and a list of n integers, find all distinct sums using numbers from the list that add up to t. for example, if t = 4, n = 6, and the list is [,], then there are four different sums that equal 4: + + 2, and 2 + 1 + 1. (A number can be used within a sum as every times as it appears in the list, and a single number counts as a sum .) your job is to solve this problem in general.
 
InputThe input will contain in one or more test cases, one per line. each test case contains t, the total, followed by n, the number of integers in the list, followed by n integers x1 ,..., xn. if n = 0 it signals the end of the input; otherwise, t will be a positive integer less than 1000, n will be an integer between 1 and 12 (random SIVE ), and x1 ,..., xn will be positive integers less than 100. all numbers will be separated by exactly one space. the numbers in each list appear in nonincreasing order, and there may be repetitions.
 
OutputFor each test case, first output a line ining 'sums', the total, and a colon. then output each sum, one per line; if there is no sums, output the line 'none '. the numbers within each sum must appear in nonincreasing order. A number may be repeated in the sum as usual times as it was repeated in the original list. the sums themselves must be sorted in decreasing order based on the numbers appearing in the sum. in other words, the sums must be sorted by their first number; sums with the same first number must be sorted by their second number; sums with the same first two numbers must be sorted by their third number; and so on. within each test case, all sums must be distince; the same sum connot appear twice.
 
Sample Input
4 6 4 3 2 2 1 15 3 2 1 1400 12 50 50 50 50 50 50 25 25 25 25 25 250 0
 
Sample Output
Sums of 4:43+12+22+1+1Sums of 5:NONESums of 400:50+50+50+50+50+50+25+25+25+2550+50+50+50+50+25+25+25+25+25+25
 
#include<stdio.h>#include<string.h>#include<algorithm>using namespace  std;int a[10100];int res[10100]={10000};int vis[10100],j,flag,n;void dfs(int m,int cnt){int i;if(m==0){flag=1;for(j=1;j<cnt-1;j++)printf("%d+",res[j]);printf("%d\n",res[j]);return ;}for(i=1;i<=n;i++){if(!vis[i]&&m-a[i]>=0&&a[i]<=res[cnt-1]){vis[i]=1;res[cnt]=a[i];dfs(m-a[i],cnt+1);vis[i]=0;while(a[i]==a[i+1]&&i<=n)++i;}}}int main(){int m,i,j;while(scanf("%d%d",&m,&n),(m||n)){for(i=1;i<=n;i++)scanf("%d",&a[i]);flag=0;printf("Sums of %d:\n",m);memset(vis,0,sizeof(vis));dfs(m,1);if(!flag)printf("NONE\n");}}
Hangdian 1016, prime ring problem, Joseph ring:

Problem DescriptionA ring is compose of n circles as shown in digoal. put natural number 1, 2 ,..., n into each circle separately, and the sum of numbers in two adjacent circles shoshould be a prime.

Note: the number of first circle shoshould always be 1.


 
Inputn (0 <n <20 ).
 
OutputThe output format is shown as sample below. each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. the order of numbers must satisfy the above requirements. print solutions in lexicographical order.

You are to write a program that completes abve process.

Print a blank line after each case.
 
Sample Input
68
 
Sample Output
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2
 
Code:

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;int vis[30],a[30],m,n;int is(int n){for(int i=2;i*i<=n;i++)if(n%i==0)return 0;return 1;}void dfs(int n,int c){if(c==n){if(is(a[n]+1)){printf("1");for(int i=2;i<=n;i++)printf(" %d",a[i]);printf("\n");}return ;}for(int i=2;i<=n;i++){if(!vis[i]&&is(a[c]+i)){a[c+1]=i;vis[i]=1;dfs(n,c+1);vis[i]=0;}}}int main(){int flag=1;while(~scanf("%d",&n)){memset(vis,0,sizeof(vis));printf("Case %d:\n",flag++);vis[1]=1;a[1]=1;dfs(n,1);printf("\n");}return 0;}
Hangzhou power 2553, n queen's question:

Problem Description places N queens on the square board of N * N so that they do not attack each other (that is, two queens are not allowed to be in the same row, the same column, it is not allowed to be on a diagonal line with 45 corners of the checker border.
Your task is to determine the number of valid placement methods for the given N.


There are several Input rows. Each row has a positive integer of N ≤ 10, indicating the number of the Board and the Queen. If N = 0, it indicates the end.
There are several rows in Output. Each row has a positive integer, indicating the number of different places corresponding to the queen of the input row.
Sample Input
1850
 
Sample Output
19210
Code:

# Include <stdio. h> # include <math. h> int x [15]; // array x indicates the position of the column, subscript indicates the column, and value indicates the row where int sum, n is placed; bool place (int v) {int I; for (I = 1; I <v; ++ I) {if (x [I] = x [v] | abs (x [I]-x [v]) = abs (I-v )) // If the row is the same or in the diagonal line (why is it not determined whether it is the same column? It is mainly because the array x indicates the position of the column) return 0;} return 1;} void backtrack (int v) {int I; if (v> n) // after the last queen is placed successfully, sum ++; else {for (I = 1; I <= n; ++ I) // find n queens {x [v] = I; if (place (v) {backtrack (v + 1) ;}}} int main () {int ans [15]; for (n = 1; n <= 10; ++ n) {sum = 0; backtrack (1); ans [n] = sum ;} while (scanf ("% d", & n), n) {printf ("% d \ n", ans [n]);} return 0 ;}






Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.