C# 1,3,5,7 排列组合(3位) 非递归

本文通过C#实现深度优先搜索(DFS)与广度优先搜索(BFS),展示了两种不同搜索策略的具体应用。DFS使用堆栈进行节点存储并深入探索,而BFS则采用队列确保按层次遍历节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//深度优先
class Program
{
static void Main(string[] args)
{
int[] number = new int[] { 1, 3, 5, 7 };
List data = new List();
Stack openStack = new Stack();
Tree root = new Tree();
Tree parent =root;
while (true)
{

if (parent.GetDeep() == 4)
{
parent.printf();

}
else
{
var tempSon= number.ToList();
foreach (var item in tempSon)
{
Tree Node = new Tree();
Node.NodeData = item;
Node.Parent = parent;
openStack.Push(Node);
}
}
if (openStack.Count == 0)[color=darkred][/color]
break;
var itemData= openStack.Pop();
parent = itemData;

}
System.Console.Read();

}
public static void printf(List data)
{
string d="";
data.ForEach(p => d = d + p);
System.Console.WriteLine(d);
}
}
class Tree
{
public Tree Parent;
public int NodeData;
public List Son = new List();
public int GetDeep()
{
int i=0;
var p=this;
while (true)
{
if (p == null)
{
return i;
}
else
{
p = p.Parent;
i++;

}

}

}
public void printf()
{
string pf = "";
var p = this;
while (true)
{
if (p == null)
{
System.Console.WriteLine(pf);
return;
}
else
{
if (p.NodeData != 0)
{
pf = p.NodeData + pf;
}
p = p.Parent;
}
}

}
}
//广度优先
class Program
{
static void Main(string[] args)
{
int[] number = new int[] { 1, 3};
List<int> data = new List<int>();
Stack<Tree> openStack = new Stack<Tree>();
Queue<Tree> openQueue = new Queue<Tree>();

Tree root = new Tree();
Tree parent =root;
while (true)
{

if (parent.GetDeep() == 4)
{
parent.printf();

}
else
{
var tempSon= number.ToList();
foreach (var item in tempSon)
{
Tree Node = new Tree();
Node.NodeData = item;
Node.Parent = parent;
// openStack.Push(Node);
openQueue.Enqueue(Node);
}
}
if (openQueue.Count == 0) //if (openStack.Count == 0)
break;
var itemData = openQueue.Dequeue(); //openStack.Pop();
parent = itemData;


}
System.Console.Read();


}

public static void printf(List<int> data)
{
string d="";
data.ForEach(p => d = d + p);
System.Console.WriteLine(d);
}

}
class Tree
{
public Tree Parent;
public int NodeData;
public List<Tree> Son = new List<Tree>();
public int GetDeep()
{
int i=0;
var p=this;
while (true)
{
if (p == null)
{
return i;
}
else
{
p = p.Parent;
i++;

}

}

}
public void printf()
{
string pf = "";
var p = this;
while (true)
{
if (p == null)
{
System.Console.WriteLine(pf);
return;
}
else
{
if (p.NodeData != 0)
{
pf = p.NodeData + pf;
}
p = p.Parent;
}

}

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值