blisle   2년 전

질문게시판에 있는 반례들 입력해봤는데 정상 출력 됩니다,,, 반례 찾아주실 고수님 구합니다

gojgho   2년 전

count  값이 q 에 추가된 횟수만큼 늘어나기때문에 틀린코드가 맞습니다.

bfs 쓰실려면 아래코드 참고해보세요

package bj.graph;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class bj16953_bfs {

  static int start, target;
  static long answer = Integer.MAX_VALUE;

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    start = sc.nextInt();
    target = sc.nextInt();

    bfs(start);
    if(answer == Integer.MAX_VALUE) {
      answer = -1;
    }
    System.out.println(answer);
  }

  private static void bfs(int start) {
    Queue<Point> q = new LinkedList<>();

    q.add(new Point(start, 1));

    while(!q.isEmpty()) {
      Point poll = q.poll();

      if(poll.pos > target) continue;
      if(poll.pos == target) {
        answer = Math.min(answer, poll.cnt);
        continue;
      }

      q.add(new Point(poll.pos * 2, poll.cnt + 1));
      q.add(new Point(Long.parseLong(poll.pos + "1"), poll.cnt + 1));

    }

  }

  static class Point {
    long pos;
    long cnt;

    Point(long pos, long cnt) {
      this.pos = pos;
      this.cnt = cnt;
    }
  }

}

댓글을 작성하려면 로그인해야 합니다.