BFS 구현(C++)

2025. 4. 14. 20:04·개발/알고리즘
728x90
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_set>
#include <unordered_map>

using namespace std;

/*
* 너비 우선 탐색으로 모든 노드를 순회하는 함수 solution()을 작성하세요.
* 시작 노드는 정수형 start로 주어집니다. graph 배열은 [출발 노드, 도착 노드] 쌍이 들어 있는 배열입니다.
* 반환값은 그래프의 시작 노드부터 모든 노드를 너비 우선 탐색한 경로가 순서대로 저장된 배열입니다.
*/


unordered_map<int, vector<int>> adjList;
vector<int> result;

void bfs(int start)
{
	unordered_set<int> visited;
	queue<int> q;

	// 시작 노드 방문
	q.push(start);
	visited.insert(start);
	result.push_back(start);
	
	while (!q.empty())
	{
		int node = q.front();
		q.pop();

		// 현재 노드의 인접 노드 중 아직 방문하지 않은 노드 방문
		for (const auto& neighbor : adjList[node])
		{
			if (visited.find(neighbor) == visited.end())
			{
				q.push(neighbor);
				visited.insert(neighbor);
				result.push_back(neighbor);
			}
		}
	}
}

vector<int> solution(vector<pair<int, int>> graph, int start)
{
	// 인접 리스트 생성
	for (const auto& edge : graph)
	{
		int u = edge.first;
		int v = edge.second;
		adjList[u].push_back(v);
	}

	// 시작 노드부터 bfs 시작
	bfs(start);

	return result;
}

int main()
{
	solution({ {1, 2}, {1, 3}, {2, 4}, {2, 5}, {3, 6}, {3, 7}, {4, 8}, {5, 8}, {6, 9}, {7, 9} }, 1);

	for (int i = 0; i < result.size(); i++)
	{
		cout << result[i];
	}

	return 0;
}

 

  • 인접 리스트를 활용해서 너비 우선 탐색 구현

'개발 > 알고리즘' 카테고리의 다른 글

[프로그래머스] 타겟 넘버(C++)  (1) 2025.04.19
[백준] 2606번: 바이러스(C++)  (2) 2025.04.18
[프로그래머스] 미로 탈출(C++)  (1) 2025.04.17
[프로그래머스] 게임 맵 최단거리(C++)  (1) 2025.04.15
DFS 구현 (C++)  (0) 2025.04.14
'개발/알고리즘' 카테고리의 다른 글
  • [백준] 2606번: 바이러스(C++)
  • [프로그래머스] 미로 탈출(C++)
  • [프로그래머스] 게임 맵 최단거리(C++)
  • DFS 구현 (C++)
Majangnan
Majangnan
  • Majangnan
    개발 모코코
    Majangnan
  • 전체
    오늘
    어제
    • 분류 전체보기 (75)
      • 개발 (74)
        • C# (10)
        • SQL (3)
        • Unity (9)
        • Unreal (10)
        • C++ (3)
        • Server (1)
        • DX11 (8)
        • 알고리즘 (29)
  • 블로그 메뉴

    • 홈
    • 방명록
    • 깃허브
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    sql
    dx3d
    프로그래머스
    Unity
    DirectX11
    코딩테스트
    알고리즘
    상속
    blueprint
    MAC
    UnReal
    Mecanim
    백준
    C#
    언리얼
    슈팅게임
    DX11
    블루프린트
    3dlight
    c++
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Majangnan
BFS 구현(C++)
상단으로

티스토리툴바