深度优先遍历

时间:2020-06-21 09:48:15   收藏:0   阅读:45

就是dfs,有个好听的名字叫回溯,其实就是穷举法,这种算法的时机复杂度为n^level ,效率还是很低的

import java.util.Stack;

public class DFSTest {

public static void main(String[] args) {
char[] p = {‘A‘,‘B‘,‘C‘};
boolean[] pb = new boolean[p.length];
dfs(p,pb,new Stack<>());
}

private static void dfs(char[] p,boolean[] pb,Stack<Character> res){
if(res.size() == p.length ){
System.out.println(res);
return;
}
for (int i = 0; i < p.length; i++) {
char c = p[i];
if(!pb[i]){
res.push(c);
pb[i] = true;
dfs(p,pb,res);
res.pop();
pb[i] = false;
}
}
}
}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!