[백준] 스타트링크 5014

Soohyeon B·2022년 11월 30일
0

BFS

목록 보기
3/3
  • 총 F층, 스타트링크 G층 , 강호가 있는곳 S층, G층이 목표
  • 엘베에는 버튼이 두개밖에 없음 U:위로 U층가기 D:아래로 D층 가기
  • S에서 G층에 도달하려면 눌러야하는 버튼의 최소 수
  • 도착할 수 없으면 use the stairs 출력

풀이 1 -31%에서 틀린 코드

#include <bits/stdc++.h>
using namespace std;

#define X first
#define Y second

int F, S, G, U, D;
int dist[1000001];

int main(void) {
  ios::sync_with_stdio(0);
  cin.tie(0);
  
  cin >> F>>S>>G>>U>>D;
  
  //10층짜리 건물 /S층에서 G층까지 가야함
  //위로 2층, 아래로 1층
  int dx[2] ={U, D*-1};
  
  queue<int> Q;
  dist[S]=0;
  Q.push(S);
  
  while(!Q.empty()){
      int cur = Q.front();
      Q.pop();
      
      for(int dir=0; dir<2; dir++){
          int next = cur+dx[dir];
          
          //범위 확인
          if(next<=0 || next>F) continue;
          //방문여부 확인
          if(dist[next]>0) continue;
          
          dist[next] = dist[cur]+1;
          Q.push(next);
      }
  }
  
  if(dist[G]==0) cout <<"use the stairs";
  else cout << dist[G];
  
}

현재 동호가 있는 층수와 스타트 링크가 있는 층수가 같은 경우를 못걸러준다.

풀이 2 - 시작점과 끝점이 같을 경우를 고려한 풀이 66%에서 틀린 코드

#include <bits/stdc++.h>
using namespace std;

#define X first
#define Y second

int F, S, G, U, D;
int dist[1000001];

int main(void) {
  ios::sync_with_stdio(0);
  cin.tie(0);
  
  cin >> F>>S>>G>>U>>D;
  
  //10층짜리 건물 /S층에서 G층까지 가야함
  //위로 2층, 아래로 1층
  int dx[2] ={U, D*-1};
  
  //출발점 저장
  queue<int> Q;
  dist[S]=0;
  Q.push(S);
  
  if(S==G) {cout << 0; return 0;}
  
  while(!Q.empty()){
      int cur = Q.front();
      Q.pop();
      
      for(int dir=0; dir<2; dir++){
          int next = cur+dx[dir];
          
          //범위 확인
          if(next<=0 || next>F) continue;
          //방문여부 확인
          if(dist[next]!=0) continue;
          
          dist[next] = dist[cur]+1;
          Q.push(next);
      }
  }
  
  if(dist[G]==0) cout <<"use the stairs";
  else cout << dist[G];
  
}

음..
출발한 후 출발점을 다시 지나가는 경우를 고려하지 않음

풀이 3 - 맞은 코드

#include <bits/stdc++.h>
using namespace std;

#define X first
#define Y second

int F, S, G, U, D;
int dist[1000001];

int main(void) {
  ios::sync_with_stdio(0);
  cin.tie(0);
  
  cin >> F>>S>>G>>U>>D;
  
  //10층짜리 건물 /S층에서 G층까지 가야함
  //위로 2층, 아래로 1층
  int dx[2] ={U, D*-1};
  
  //출발점 저장
  queue<int> Q;
  dist[S]=1;
  Q.push(S);
  
  if(S==G) {cout << 0; return 0;}
  
  while(!Q.empty()){
      int cur = Q.front();
      Q.pop();
      
      for(int dir=0; dir<2; dir++){
          int next = cur+dx[dir];
          
          //범위 확인
          if(next<=0 || next>F) continue;
          //방문여부 확인
          if(dist[next]!=0) continue;
          
          dist[next] = dist[cur]+1;
          Q.push(next);
      }
  }
  
  if(dist[G]==0) cout <<"use the stairs";
  else cout << dist[G]-1;
  
}
profile
하루하루 성장하는 BE 개발자

0개의 댓글