vidigummy KAU/알고리즘 공부(백준!)

그래프 (BFS, DFS 구현)

vidi 2020. 7. 30. 21:51

백준님 코드는 최고야... 짜릿해... 많이 배워갑니다.

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

vector<vector<int>> arr;
bool* check;
queue<int> q;

/*
//인접 행렬
void dfs(int n,int x)
{
	check[x] = true;
	cout << x << " ";
	for (int i = 1; i <= n; i++)
	{
		if (arr[x][i] == 1 && check[i] == false)
		{
			dfs(n, i);
		}
	}
}
*/

/*
//인접 리스트
void dfs(int x)
{
	check[x] = true;
	cout << x << " ";
	for (int i = 0; i < arr[x].size(); i++)
	{
		int y = arr[x][i];
		if (check[y] == false)
		{
			dfs(y);
		}
	}
}
*/



int main()
{

	/*
	int a[10][10];
	//인접행렬10*10
	int n, m;
	cin >> n >> m;
	for (int i = 0; i < m; i++)
	{
		int u, v;
		cin >> u >> v;
		a[u][v] = a[v][u] = 1;
	}
	for (int i = 0; i < m; i++)
	{
		for (int j = 0; j < m; j++)
		{
			cout << a[i][j] << " ";
		}
		cout << "\n";
	}
	*/
	
	//인접 리스트
	int n, m;
	cin >> n >> m;
	arr = vector<vector<int>>(n+1);
	check = new bool(n + 2) ;
	for (int i = 0; i <= n; i++)
	{
		check[i] = false;
	}

	for (int i = 0; i < m; i++)
	{
		int u, v;
		cin >> u >> v;
		arr[u].push_back(v);
		arr[v].push_back(u);
	}

	/*
	//BFS 인접 리스트
	check[1] = true; q.push(1);
	while (!q.empty())
	{
		int x = q.front(); q.pop();
		cout << x << " ";
		for (int i = 0; i < arr[x].size(); i++)
		{
			int y = arr[x][i];
			if (check[y] == false)
			{
				check[y] = true;
				q.push(y);
			}
		}
	}
	*/


	/*
	//출력 예시
	for (int i = 1; i <= n; i++)
	{
		cout << i << " : ";
		while (!arr[i].empty())
		{
			cout << arr[i].back() << " ";
			arr[i].pop_back();
		}
		cout << endl;
	}
	*/
	/*
	//인접 리스트 DFS 출력 예시
	cout << endl << "DFS!\n";
	dfs(1);
	*/
	return 0;
}