Search
Duplicate
📗

텔레포트 정거장

주차
문제번호
18232
언어
C++
티어
실버
유형
그래프
BFS
nj_Blog
nj_상태
이해도
100%
풀이
사람
이해도 2
13 more properties

문제접근

인접 리스트 방식으로 그래프 초기화
양 옆도 초기화
bfs로 탐색하면서 visited에 방문을 체크할겸 거리 계산
visited[e]를 접근하면 e까지 거리

놓쳤던 부분

station을 resize 해두고 push_back을 진행하여 메모리 초과

코드

26860 KB

364 ms

#include <iostream> #include <vector> #include <queue> #include <utility> using namespace std; int s,e; vector<vector<int> > station; vector<int> visited; void bfs() { queue<int> q; q.push(s); visited[s] = 0; while(!q.empty()) { int currentStation = q.front(); q.pop(); for (unsigned int i = 0; i < station[currentStation].size(); i++) { int nextStation = station[currentStation][i]; if (visited[nextStation] != -1) continue ; visited[nextStation] = visited[currentStation] + 1; q.push(nextStation); } } } int main(void) { int n,m; int x,y; ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m; cin >> s >> e; station.resize(n + 1); visited.resize(n + 1, -1); for (int i = 0; i < m; i++) { cin >> x >> y; station[x].push_back(y); station[y].push_back(x); } for (int i = 1; i <= n; i++) { if (i + 1 <= n) { station[i].push_back(i + 1); station[i + 1].push_back(i); } if (i - 1 >= 2) { station[i].push_back(i - 1); station[i - 1].push_back(i); } } bfs(); cout << visited[e]; return (0); }
C++
복사