안선생의 개발 블로그

graphs 본문

알고리즘

graphs

안선생 2022. 11. 27. 16:52

graphs.cpp

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
#include <iostream>
#include "queue.h"
using namespace std;
 
void bfs(int g[][7], int start, int n)
{
    int i = start;
    int visited[7= { 0 };
    cout << i << " ";
    visited[i] = 1;
    enqueue(i);
 
    while (!isempty())
    {
        i = dequeue();
        for (int j = 1; j < n; j++)
        {
            if(g[i][j] == 1 && visited[j] == 0)
            {
                cout << j << " ";
                visited[j] = 1;
                enqueue(j);
            }
        }
    }
}
void dfs(int g[][7], int start, int n)
{
    static int visited[7= { 0 };
 
    if (visited[start] == 0)
        cout << start << " ";
    visited[start] = 1;
    for (int j = 1; j < n; j++)
    {
        if (g[start][j] == 1 && visited[j] == 0)
            dfs(g, j, n);
    }
}
int main()
{
    int g[7][7= { {0,0,0,0,0,0,0},
                   {0,0,1,1,0,0,0},
                   {0,1,0,0,1,0,0},
                   {0,1,0,0,1,0,0},
                   {0,0,1,1,0,1,1},
                   {0,0,0,0,1,0,0},
                   {0,0,0,0,1,0,0,} };
 
    bfs(g, 47);
    return 0;
}
cs

queue.h

 

 

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
#include<iostream>
using namespace std;
 
struct Node
{
    int data;
    Node* next;
}*front=NULL,*rear=NULL;
 
void enqueue(int x)
{
    Node* t;
    t = new Node;
    if (t == NULL)
        cout << "full";
    else
    {
        t->data = x;
        t->next = NULL;
        if (front == NULL)
        {
            front = rear = t;
        }
        else
            rear->next=t;
        rear = t;
 
    }
}
 
 
int dequeue()
{
    int x = -1;
    Node* t;
    if (front == NULL)
        cout << "Queue is Empty";
    else
    {
        x = front->data;
        t = front;
        front = front->next;
        free(t);
    }
    return x;
}
 
int isempty()
{
    return front == NULL;
}
 
cs

'알고리즘' 카테고리의 다른 글

chaining  (0) 2022.11.27
hashing  (0) 2022.11.27
sort 정렬  (0) 2022.11.27
heap  (0) 2022.11.27
BST  (0) 2022.11.27