[Search] depth-first search base model

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/shipsail/article/details/90081878

Application of the whole arrangement in the depth-first

Description of problem

Full array of N consecutive natural numbers.
Deformation:
there are N cards (1,2,3,4, ..., n), to obtain all possible permutations.
Box arrangement to the N

The idea of ​​a

At a first time is certainly conceivable enumeration method, a loop through all possible for
each possible box are N, then treated with N layers, each of the final number N is determined to not be repeated.
Chengdu is the time complexity of O (N ^ 9), it will take up a lot of time and write code becomes very complicated.

Reading topic

  1. There are N numbers, each cassette has possibilities into N
  2. An artifact: Small priorities into
  3. Determining whether the card has been placed

The idea of ​​two

I still think the beginning of the for loop
is probably thinking:

//第一个盒子N种可能
当前位置=1;
for(int i=1;i<=N;i++){
	if(没被放入){
	 	放入当前盒子
		当前位置=2;//下一个
		//第二个盒子N种可能
		for(int i2=1;i2<=N;i2++){
			if(没有放入){
				放入当前盒子
				当前位置=3;//下一个
				........
				//第N个盒子
				for(int iN=1;iN<=N;iN++){....结束的标志} 
				当前位置-1;//返回 N-1层
			}
		}
		当前位置-1; //for2层结束返回for1层
	}
}
//程序结束

Obviously, this does not reduce the burden of programming, and once the value of N changes, you have to modify the code ... Anyway, I do not want to do it haha.

Analysis of this code can be found in the task execution cycles for each layer is the same: to find the minimum number of currently been put in a no, then jump to the next layer, drained and then a layer of a group of arrayed layer jump back. A set of ordered end flag: current position jump N + 1 (N + 1 itself is not present)

The idea three

And that brings me "recursive" programming:

  1. Repeating code segment processing the same tasks
  2. There completion flag

Layer by layer can also think of the return recursion, recursive function kind of return to return to the first call to this function of position, that is returned to the previous level.


int box[10],book[10],N=5;
//解决第step个盒子前的组合问题
void df(int step){
	//结束标志
	if(step == N+1){
		//打印盒子数组种的值
		for(int i=1;i<=N;i++)
			cout<<box[i];
		cout<<endl;
		return;//返回上一层
	}
	
	//遍历N种可能
	for(int i=1;i<=N;i++){
		//判断是否被占用,判断是否被标记
		if(book[i]!=1){
			//放入
			box[step] = i;
			//置标记
			book[i]=1;
			//跳入下一层
			df(step +1);
			//跳回本层
			book[i]=0;//拿出卡片,继续循环
		}
	}
	return;//跳回上一层
}

Depth-first search

The basic idea is actually more limited search depth model

void dfs(int step){
	判断边界
	尝试每一种可能{
		继续下一步 ;
	}
	全部完成返回上一步
}

In fact, I personally feel that recursion is hard, mainly to seize the incoming parameters, repeat the code segment, and ending conditions.

Guess you like

Origin blog.csdn.net/shipsail/article/details/90081878