public static void ShaoMiaoExit(List<AHT> listAHT, AHT cur, List<int[]> solutionlist) { int hight = 0; int right = 0; foreach (var aht in listAHT) { if (aht.right >= right) { right = aht.right; if (aht.hight > cur.hight && right > cur.left) { hight = aht.hight; } } } for (int i = listAHT.Count - 1; i >= 0; i--) { if (listAHT[i].right < cur.left) { listAHT.Remove(listAHT[i]); } } solutionlist.Add(new int[] { right, hight }); }
/// <summary> /// 利用扫描线算法 /// </summary> /// <param name="buildings"></param> /// <returns></returns> public static IList<int[]> GetSkyline2(int[,] buildings) { List<int[]> solutionlist = new List<int[]>(); List<int[]> LastSolutionlist = new List<int[]>(); if (buildings == null) return solutionlist; if (buildings.Length == 0) { return solutionlist; } List<AHT> listAHT = new List<AHT>(); solutionlist.Add(new int[] { buildings[0, 0], buildings[0, 2] }); AHT aht = new AHT(); aht.left = buildings[0, 0]; aht.right = buildings[0, 1]; aht.hight = buildings[0, 2]; listAHT.Add(aht); var maxRigth = aht.right; for (int i = 1; i < buildings.GetLength(0); i++) { aht = new AHT(); aht.left = buildings[i, 0]; aht.right = buildings[i, 1]; aht.hight = buildings[i, 2]; if (maxRigth < aht.right) { maxRigth = aht.right; } ShaoMiaoEntrance(listAHT, aht, solutionlist); } solutionlist.Add(new int[] { maxRigth, 0 }); for (int i = 0; i < solutionlist.Count; i++) { if (i != 0 && solutionlist[i][1] == solutionlist[i - 1][1]) { continue; } //if (i == solutionlist.Count - 1 && solutionlist[i][0] == solutionlist[i - 1][0]) //{ // LastSolutionlist[LastSolutionlist.Count - 1][1] = 0; //} if (i != 0 && solutionlist[i][0] == LastSolutionlist[LastSolutionlist.Count - 1][0]) { if (i == solutionlist.Count - 1) { if (LastSolutionlist[LastSolutionlist.Count - 1][0] == solutionlist[i - 1][0]) { LastSolutionlist[LastSolutionlist.Count - 1][1] = 0; continue; } } else if (solutionlist[i][1] > solutionlist[i - 1][1]) { LastSolutionlist[LastSolutionlist.Count - 1][1] = solutionlist[i][1]; continue; } else { continue; } } LastSolutionlist.Add(solutionlist[i]); } return LastSolutionlist; }
public static void ShaoMiaoEntrance(List<AHT> listAHT, AHT cur, List<int[]> solutionlist) { int hight = cur.hight; int left = cur.left; int current = 0; while (current < listAHT.Count) { if (listAHT[current].right >= left) { if (listAHT[current].right > cur.right) { if (listAHT[current].hight > hight) { hight = listAHT[current].hight; left = listAHT[current].right; } } else { if (listAHT[current].hight > hight) { left = listAHT[current].right; } } } //产生拐点 if (listAHT[current].right < cur.left) { ShaoMiaoExit(listAHT, cur, solutionlist); } current++; } solutionlist.Add(new int[] { left, hight }); listAHT.Add(cur); }