VioletaBabel

64. 우선순위 큐 (C#) 본문

BCA/1. C,C++,C#
64. 우선순위 큐 (C#)
Beabletoet 2018. 8. 10. 14:21

C#엔 우선순위 큐가 안보이더라. AStar를 유니티 상에서 짜려는데 있는게 훨씬 편할 것 같아서 작업 제대로 들어가기 전에 먼저 짜보았다.

단, 내가 필요한 건 값이 작은 애부터 나오는 애. 큰 애부터 나오게 하려면 pop 함수에서 앞이 아닌 뒤부터 나오게 하면 된다.


노드를 담은 아이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class GridData : MonoBehaviour
{
    public int f;
    public static bool operator <(GridData g1, GridData g2)
    {
        return (g1.f < g2.f);
    }
 
    public static bool operator >(GridData g1, GridData g2)
    {
        return (g1.f > g2.f);
    }
 
    public static bool operator <=(GridData g1, GridData g2)
    {
        return (g1.f <= g2.f);
    }
 
    public static bool operator >=(GridData g1, GridData g2)
    {
        return (g1.f >= g2.f);
    }
 
    public static bool operator ==(GridData g1, GridData g2)
    {
        return (g1.f == g2.f);
    }
 
    public static bool operator !=(GridData g1, GridData g2)
    {
        return (g1.f != g2.f);
    }
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class AStar : MonoBehaviour
{
    private void Start()
    {
        /*테스트코드
        Priority_Queue<GridData> g = new Priority_Queue<GridData>();
        GridData g1 = new GridData();
        g1.f = 10;
        g.push(g1);
        GridData g2 = new GridData();
        g2.f = 23;
        g.push(g2);
        GridData g3 = new GridData();
        g3.f = 2;
        g.push(g3);
        GridData g4 = new GridData();
        g4.f = 4;
        g.push(g4);
        GridData g5 = new GridData();
        g5.f = 16;
        g.push(g5);
        print(g.count);
        for (int i = 0; i < 5; ++i)
            print(i.ToString()+":"+ g.pop().f.ToString());
        print(g.count);
        */
    }
}
 
public class Priority_Queue<T>
{
    List<GridData> nowList;
 
    public Priority_Queue()
    {
        nowList = new List<GridData>();
    }
 
    public void push(GridData data)
    {
        int count = nowList.Count;
        int index = -1;
        if (count < 1)
        {
            nowList.Add(data);
            return;
        }
        for (int i = count; --> -1;)
            if (nowList[i] < data)
            {
                index = i + 1;
                break;
            }
        if (index.Equals(-1))
            index = 0;
        nowList.Insert(index, data);
    }
 
    public GridData pop()
    {
        GridData g = nowList[0];
        nowList.RemoveAt(0);
        return g;
    }
 
    public int count
    {
        get
        {
            return nowList.Count;
        }
    }
}
cs


Comments