安排课程
-
输入: prerequisite={{1},{3},{3},{}}
-
解释:一共有四门课,编号分别为0、1、2、3,第0门需要完成第1门课,第1门课需要先完成第3门课,第2门需要完成第3门课
-
思路:1、preClass数量不能动,动了顺序就不对了
2、创建List YGcount 用于记录已经上过的课程,如果上过的课程=课程总数,跳出
3、如果preClass里的预备上的课程为0,上过的课程+1 -
代码:
class ArrangClass
{public void ClassMain() { //安排课程 // 输入: prerequisite ={ { 1},{ 3},{ 3},{ } } // 解释:一共有四门课,编号分别为0、1、2、3,第0门需要完成第1门课,第1门课需要先完成第3门课,第2门需要完成第3门课 List<List<int>> Zlist = new List<List<int>>(); List<int> list1 = new List<int>(); list1.Add(1); List<int> list2 = new List<int>(); list2.Add(3); List<int> list3 = new List<int>(); list3.Add(3); list3.Add(0); List<int> list4 = new List<int>(); list4.Add(1); List<int> list5 = new List<int>(); Zlist.Add(list1);//0 Zlist.Add(list2);//1 Zlist.Add(list3);//2 Zlist.Add(list4);//3 Zlist.Add(list5);//4 string strClass = string.Empty; List<int> Remove = new List<int>(); bool ifSet = true; ArrangeClasses(Zlist, ref strClass, Remove,ref ifSet); if (!ifSet) { Console.WriteLine("死循环!"); } else { Console.WriteLine(strClass.Trim('-')); } } private void ArrangeClasses(List<List<int>> Zlist, ref string strClass, List<int> Remove,ref bool ifSet) { ifSet = false; for (int i=0;i< Zlist.Count; i++) { if (Zlist[i].Count == 0) { if (!Remove.Contains(i)) { Remove.Add(i); ifSet = true; strClass += i + "-"; } } } for (int j = 0; j < Remove.Count; j++) { for (int i = 0; i < Zlist.Count; i++) { for(int k=0;k< Zlist[i].Count; k++) { if(Remove[j]== Zlist[i][k]) { Zlist[i].Remove(Remove[j]); } } } } for (int i = 0; i < Zlist.Count; i++) { if (ifSet) { ArrangeClasses(Zlist, ref strClass, Remove, ref ifSet); } } }
}