/**
* 构建计划树
* @author lang yong
*
*/
public class PlanTree {
public static int solutionNum = 0;//解决方案数量
private PlanNode root;//根元素
private String[][] plan;//存储休假计划的二维数组
public PlanNode getRoot() {
return root;
}
public PlanTree(String[][] plan){
this.root = new PlanNode("");//构建根元素
this.plan = plan;
this.buildTree();//构建计划树
}
public void buildTree(){
buildTree(root,plan,0);
}
/**
*
* @param node 当前节点
* @param weekdays 休假计划数组
* @param deep 树的深度
*/
public void buildTree(PlanNode node,String[][] weekdays,int deep){
if(deep > weekdays.length -1 )return;
for(String weekday:weekdays[deep]){
PlanNode tNode = new PlanNode(weekday);
node.addChild(tNode);
buildTree(tNode, weekdays, deep+1);//递归地构建树
}
}
public static void main(String[] args) {
new PlanTree(new String[][]{
{"星期一","星期六"},
{"星期二","星期四"},
{"星期三","星期日"},
{"星期五"},
{"星期一","星期四","星期六"},
{"星期二","星期五"},
{"星期三","星期六","星期日"},
}).getRoot().traverse("");
}
}
class PlanNode{
private List
private String name;
public PlanNode(String name){
children = new ArrayList
this.name = name;
}
public PlanNode addChild(PlanNode child){
children.add(child);
return this;
}
/**
* 是否叶子节点
* @return
*/
public boolean isLeaf(){
return this.children.size() == 0;
}
/**
* 递归地遍历树,并在遍历过程中判断如果抵达叶子节点,就输出满足条件的安排内容
* @param planS
*/
public void traverse(String planS){
if(planS.indexOf(this.name) > 0){
return;
}
planS += this.name + " ";
if(this.isLeaf()){
System.out.println("Solution " + ++PlanTree.solutionNum + ":");
System.out.println("钱 赵 孙 李 周 吴 陈 ");
System.out.println("==============================================");
System.out.println(planS.trim());
System.out.println("");
}
for(PlanNode child : children){
child.traverse(planS);
}
}
}
感觉好像离散中安排飞行员飞行时间的那个题