SW 중심대학 OSS GIT 서버 박건태, 이승준, 고기완, 이준호 새로운 배포
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.3 KiB

4 years ago
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Test_Algo : MonoBehaviour
  5. {
  6. private static int INF = 1000000000; //무한대를 표현하기 위해 int 형은 21억정도의 양수의 값을 가질수 있기때문에
  7. private static int number = 6; //정점의 갯수
  8. public GameObject gss;
  9. bool[] v = new bool[6]; //방문한 노드
  10. int[] d = new int[6]; //최단 거리
  11. private GameObject ga;
  12. //x좌표y 좌표
  13. int[,] a = new int[6, 6] { //즉 distance 값
  14. {0,4,6,5,INF,INF},
  15. {4,0,INF,3,3,INF},
  16. {6,INF,0,5,INF,7},
  17. {5,3,5,0,INF,3},
  18. {INF,3,INF,INF,0,6},
  19. {INF,INF,7,3,6,0},};
  20. int[] x = new int[5];
  21. int[] z = new int[5];
  22. //가장 비용이 적은 노드를 구해옴
  23. public void Start()
  24. { // x 와 z 의 Transform 위치값
  25. x[0] = 0; x[1] = 0; x[2] = 6; x[3] = 3; x[4] = 7; x[5] = 6;
  26. z[0] = 0; z[1] = 4; z[2] = 0; z[3] = 4; z[4] = 0; z[5] = 7;
  27. dijkstra(0); //
  28. for (int i = 0; i < number; i++)
  29. {
  30. Debug.Log(d[i]);
  31. }
  32. }
  33. int getSmallIndex()
  34. {
  35. int min = INF;
  36. int index = 0;
  37. //선형탐색
  38. for (int i = 0; i < number; i++)
  39. {
  40. //방문하지 않은 노드 중에서 현재 최소값보다 더 작은 거리가 존재한다면
  41. if (d[i] < min && !v[i])
  42. {
  43. //그 값으로 값을 갱신해준다,.
  44. min = d[i];
  45. //그리고 그때의 위치를 기억할수 있게 한다.
  46. index = i;
  47. }
  48. }
  49. return index;
  50. }
  51. // 다익스트라를 수행하는 함수. 시작 위치를 물어본다.
  52. void dijkstra(int start)
  53. {
  54. for (int i = 0; i < number; i++)
  55. {
  56. //d는 결과 적으로 가지는 최소비용을 담는 배열
  57. d[i] = a[start,i]; //모든 경로까지의 비용을 담아줌
  58. }
  59. v[start] = true; //시작점을 방문을 했다고 알려줌
  60. for (int i = 0; i < number - 2; i++)
  61. {
  62. int current = getSmallIndex(); //현재 방문하지 않는 노드 중에서 빠르게 도착할수 있는 비용을 가지는 노드
  63. v[current] = true; //노드를 방문 처리 해줌
  64. for (int j = 0; j < 6; j++)
  65. {
  66. //하나씩 확인 해보면서 그노드를 방문하지 않았다면,
  67. if (!v[j])
  68. {
  69. //d[current]= 노드까지의 최소비용에서, a[current][j]=노드를 거쳐서,
  70. if (d[current] + a[current,j] < d[j])
  71. {
  72. //d[j]값을 더 작은 값으로 갱신한다.
  73. d[j] = d[current] + a[current,j];
  74. }
  75. }
  76. }
  77. }
  78. }
  79. }