//Topcoder SRM 574 DIV 2 L2 TheNumberGameDiv2
import java.util.*;
import java.math.*;
import javax.crypto.spec.PSource;
public class TheNumberGameDiv2 {
public static void main(String[] args) {
System.out.println(
//
new TheNumberGameDiv2().minimumMoves(
218181918,
9181
));
}
HashSet<Integer> nums = new HashSet<Integer>();
int minmov;
public int minimumMoves(int A, int B) {
if (A == B)
return 0;
minmov = Integer.MAX_VALUE;
dfs(A, B, 0);
if (minmov == Integer.MAX_VALUE)
return -1;
else
return minmov;
}
private void dfs(int a, int b, int mov) {
if (a == b) {
minmov = Math.min(minmov, mov);
return;
}
if (a == 0)
return;
nums.add(a);
String rev = new StringBuffer(String.valueOf(a)).reverse().toString();
int arev = Integer.valueOf(rev);
if (!nums.contains(arev)) {
dfs(arev, b, mov + 1);
}
dfs(a / 10, b, mov + 1);
}
}
No comments:
Post a Comment