백준 2644 c++

magicdrill·2024년 3월 12일
0

백준 문제풀이

목록 보기
137/655

백준 2644 c++

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int result;
vector <int> graph[101];
vector <bool> visited(101, false);

void input_graph(int m)//양방향 연결
{
	int i;
	int a, b;

	for (i = 0; i < m; i++)
	{
		cin >> a >> b;
		graph[a].push_back(b);
		graph[b].push_back(a);
	}

	return;
}

void DFS(int current, int destination, int count)
{
	int i, next;

	visited[current] = true;
	//cout << current << " ";
	if (current == destination)
	{
		result = count;
		return;
	}
	else
	{
		for (i = 0; i < graph[current].size(); i++)
		{
			next = graph[current][i];
			if (visited[next] != true)
			{
				//count++;
				DFS(next, destination, count + 1);
			}
			else
			{
				;
			}
		}
	}
}

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int n, x, y, m, i;

	cin >> n;
	cin >> x >> y;
	cin >> m;
	input_graph(m);
	/*for (i = 1; i <= n; i++)
	{
		sort(graph[i].begin(), graph[i].end());
	}*/
	DFS(x, y, 0);
	if (result != 0)
	{
		cout << result << "\n";
	}
	else
	{
		cout << "-1\n";
	}

	return 0;
}

0개의 댓글