Created
March 14, 2017 13:15
-
-
Save dev-yong/75b28e0f195dea197e7827ea9a87a970 to your computer and use it in GitHub Desktop.
graph의 행렬 생성, BFS, DFS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
#include <vector> | |
#include <stack> | |
#include <queue> | |
#include <cstring> | |
using namespace std; | |
int arr[1020][1020]; | |
bool visited[1020]; | |
int vertex_num, edge_num; | |
stack <int> DFS_NUM; | |
queue <int> BFS_NUM; | |
void DFS(int start) | |
{ | |
visited[start] = true; | |
cout << start << ' '; | |
//DFS_NUM.push(start); | |
for (int i = 1; i <= vertex_num; i++) { | |
if (arr[start][i] == 1 && visited[i] == false) { | |
DFS(i); | |
} | |
} | |
//DFS_NUM.pop(); | |
} | |
void BFS(int start) | |
{ | |
visited[start] = true; | |
BFS_NUM.push(start); | |
while (BFS_NUM.empty() == false) | |
{ | |
int now_position = BFS_NUM.front(); BFS_NUM.pop(); | |
cout << now_position << ' '; | |
for (int i = 1; i <= vertex_num; i++) { | |
if (arr[now_position][i] == 1 && visited[i] == false) { | |
BFS_NUM.push(i); | |
visited[i] = true; | |
} | |
} | |
} | |
} | |
int main() | |
{ | |
int start_vertex; | |
int vertex1, vertex2; | |
cin >> vertex_num >> edge_num >> start_vertex; | |
for(int i=0; i<edge_num; i++){ | |
cin >> vertex1 >> vertex2; | |
arr[vertex1][vertex2] = arr[vertex2][vertex1] = 1; | |
} | |
DFS(start_vertex); | |
memset(visited, false, 1001); | |
cout << "\n"; | |
BFS(start_vertex); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment