CSE/baekjoon & swexpert
백준 1697 숨바꼭질 java
언제나 변함없이
2019. 5. 27. 20:16
반응형
import java.io.IOException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.lang.*;
class Pair {
int pos;
int cnt;
public Pair(int n, int c) {
pos = n;
cnt = c;
}
}
public class Main {
static boolean[] visited = new boolean [100001];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Queue<Pair> q = new LinkedList<Pair>();
int n = sc.nextInt();
int k = sc.nextInt();
q.offer(new Pair(n,0));
visited[n] = true;
while(!q.isEmpty()) {
Pair curr = q.poll();
if(curr.pos == k ) {
System.out.println(curr.cnt);
break;
}
if(isVal(curr.pos -1)) {
q.offer(new Pair( curr.pos -1, curr.cnt +1));
visited[ curr.pos -1] = true;
}
if(isVal(curr.pos +1)) {
q.offer(new Pair( curr.pos +1, curr.cnt +1));
visited[ curr.pos +1] = true;
}
if(isVal(curr.pos *2)) {
q.offer(new Pair( curr.pos *2, curr.cnt +1));
visited[ curr.pos * 2] = true;
}
}
}
static //유효한 값인지 체크
boolean isVal(int pos) {
if(pos >= 0 && pos <= 100000 && !visited[pos])
return true; //아직 안간곳입니다.
return false; //이미 탐색한 곳입니다.
}
}
연습한부분(C++)
bool visited[100'001];
struct Pos {
int pos;
int cnt;
}
//유효한가
bool isVal(int pos){
return 0 <= pos && pos <= 100'000 && !visited[pos];
}
int main(){
int n, k;
cin >>n >>k;
queue<Pos> q;
q.push({n, 0});
visited[n] = true;
while(!q.empty()){
Pos curr = q.front();
q.pop();
//해당 값이 k값과 일치하는가(답)
if(curr.pos == k){
cout << curr.cnt;
return 0;
}
//그렇지 않다면 다음에 q큐에 넣을 요소를 확인합니다.
//3가지 방향밖에 없으므로 그냥 갖다 넣을게요~
//if(isVal(next.pos){}로 감싸주세용
Pos next {curr.pos -1, curr.cnt +1};
q.push(next);
visited[next.pos] = true;
next.pos = curr.pos * 2;
}
}
반응형