Created
July 3, 2017 05:09
-
-
Save musaprg/c21f49ec452a52bf2089d09da236f8a0 to your computer and use it in GitHub Desktop.
ARC001B 幅優先
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
int A = sc.nextInt(); | |
int B = sc.nextInt(); | |
int v[] = {1, -1, 5, -5, 10, -10}; //操作 | |
//幅優先探索 | |
Queue<Integer> q = new LinkedList<Integer>(); //キュー | |
Map<Integer, Integer> hm = new HashMap<Integer, Integer>(); //遷移回数を保存 | |
q.add(A); //初期状態を入れる | |
hm.put(A, 0); //遷移回数は0 | |
while(!q.isEmpty() && !hm.containsKey(B)){ //Bのキーが現れたら終了 | |
int now = q.poll(); //今の状態を取り出す | |
int count = hm.get(now); //遷移回数 | |
for(int i = 0; i < v.length; i++){ | |
int temp = now + v[i]; //変化後の温度 | |
if(!hm.containsKey(temp)){ | |
//新しい温度が出現したとき | |
q.add(temp); | |
hm.put(temp, count+1); | |
} | |
} | |
} | |
System.out.println(hm.get(B)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment