본문 바로가기

[알고리즘개론] - Algorithm/[Concept]

알고리즘 Part 1

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
class Tree
{
public:
    int n;
    vector<int> *c; //array of dynamic array //2D array
 
    void init(const char *_fildName)
    {
        FILE *input = fopen(_fildName, "r"); // Read file
        fscanf(input, "%d"&n); // Get n from the file
        c = new vector<int>[n];
        for (int i = 0; i < n; i++)
        {
            int tmp;
            while (true)
            {
                fscanf(input, "%d"&tmp); // Get child data
                if (tmp == -1)
                    break;
                c[i].push_back(tmp);
            }
        }
        fclose(input);
    }
};
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void DFS(Tree &t)
// &t : use as like local variable
    stack<int> s;
    s.push(0); // Root index;
    while (!s.empty())
    {
        int x = s.top();
        printf("%d ", x);
        s.pop();
        // Push all child node data
        for (int i = 0; i < t.c[x].size(); i++)
        {
            s.push(t.c[x][i]);
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void BFS(Tree &t)
{
    queue<int> q;
    q.push(0);
 
    while (!q.empty())
    {
        int x = q.front();
        printf("%d ", x);
        q.pop();
        // Push all child node data
        for (int i = 0; i < t.c[x].size(); i++)
        {
            q.push(t.c[x][i]);
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
int main(int argc, char **argv)
{
    Tree t;
    t.init(argv[1]);
    DFS(t);
    BFS(t);
    return 1;
}
cs

FILE.txt

19
1 2 3 -1
4 5 6 -1
7 8 -1
9 10 -1
11 12 -1
-1
-1
-1
13 14 -1
-1
15 16 -1
-1
-1
-1
-1
17 18 -1
-1
-1
-1

'[알고리즘개론] - Algorithm > [Concept]' 카테고리의 다른 글

알고리즘 Find_Max  (0) 2020.10.20
시간측정  (0) 2020.10.17
알고리즘 Part 4  (0) 2020.10.05
알고리즘 Part 3  (0) 2020.10.05
알고리즘 Part 2  (0) 2020.10.05