개발자 피터
Peter's Dev Blog
개발자 피터
전체 방문자
오늘
어제
  • 분류 전체보기 (77)
    • 🧑🏻‍💻 Develop (13)
      • Devops (3)
      • Elasticsearch (3)
      • Design Pattern (1)
      • SQL (4)
      • Architecture (1)
      • APM (1)
    • 💻 Service (7)
      • E-ROOM (3)
      • Briefing (4)
    • 💡 Problem Solving (43)
      • Baekjoon (40)
      • Programmers (2)
    • 📚 Reading (12)
      • Tech (9)
      • Self-Help (3)
    • 💬 Etc (1)
    • 📈 Retrospective (1)

블로그 메뉴

  • 🌟 깃허브
  • 🏷️ 태그 클라우드
  • 📝 방명록

공지사항

인기 글

태그

  • E-ROOM
  • 백준
  • MySQL
  • 백트래킹
  • 브루트포스
  • 그리디
  • elasticsearch
  • 문자열
  • 독서
  • briefing
  • boj
  • Programmers
  • SQL
  • 구현
  • java

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
개발자 피터

Peter's Dev Blog

💡 Problem Solving/Baekjoon

[백준 - 1260] DFS와 BFS [C++]

2020. 4. 17. 15:06
728x90
반응형

1. 문제

https://www.acmicpc.net/problem/1260

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.

www.acmicpc.net

 

2. 풀이

: 그래프에서의 DFS와 BFS를 구현하여 해결합니다.

 

 

3. 코드

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

using namespace std;
int c[1001];
vector <int> a[1001];

void dfs(int x) {
	if(c[x]) return;
	c[x] = true;
	cout << x << " ";
	for(int i=0; i<a[x].size(); i++) {
		int y = a[x][i];
		dfs(y);
	}
}

void bfs(int start) {
	queue <int> q;
	q.push(start);
	c[start] = true;
	while(!q.empty()) {
		int x = q.front();
		q.pop();
		cout << x << " ";
		for(int i=0; i<a[x].size(); i++) {
			int y = a[x][i];
			if(!c[y]) {
				q.push(y);
				c[y] = true;
			}
		}
	} 
}

int main(void) {

	iostream::sync_with_stdio(false);
	cin.tie(NULL);
	int n, m, v, x, y;
	cin >> n >> m >> v;
	for(int i=0; i<m; i++) {
		cin >> x >> y;
		a[x].push_back(y);
		a[y].push_back(x);
	}
	for(int i=1; i<=n; i++) {
		sort(a[i].begin(), a[i].end());
	}
	dfs(v);
	for(int i=1; i<=n; i++) c[i] = false;
	cout << "\n";
	bfs(v);
	return 0;
}
728x90
반응형

'💡 Problem Solving > Baekjoon' 카테고리의 다른 글

[백준 - 10819] 차이를 최대로 [c++]  (0) 2021.01.14
[백준 - 11724] 연결 요소의 개수 [C++]  (1) 2020.04.20
[백준 - 11403] 경로찾기 [C++]  (1) 2020.04.20
[백준 - 1012] 유기농 배추 [C++]  (2) 2020.04.17
[백준 - 2667] 단지번호붙이기 [C++]  (1) 2020.04.17
    '💡 Problem Solving/Baekjoon' 카테고리의 다른 글
    • [백준 - 11724] 연결 요소의 개수 [C++]
    • [백준 - 11403] 경로찾기 [C++]
    • [백준 - 1012] 유기농 배추 [C++]
    • [백준 - 2667] 단지번호붙이기 [C++]
    개발자 피터
    개발자 피터
    Backend Engineer 🔥

    티스토리툴바