说是找最短路…..其实从一点走到另外一点的距离是固定的,都是矩形的(长-1)+(宽-1),即坐标相减。
map建图之后跑一遍就好了。
public class Main {
static String[][] list = { { "", "ABC", "DEF" }, { "GHI", "JKL", "MNO" }, { "PQRS", "TUV", "WXYZ" } };
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
HashMap<Character, Node> map = new HashMap<>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int j2 = 0; j2 < list[i][j].length(); j2++) {
map.put(list[i][j].charAt(j2), new Node(i + 1, j + 1));
}
}
}
int t = reader.nextInt();
while (t-- > 0) {
String in = reader.next();
int count = 0;
Node start = new Node(1, 1);
for (int i = 0, len = in.length(); i < len; i++) {
char get = in.charAt(i);
Node tar = map.get(get);
count += Math.abs((tar.x - start.x)) + Math.abs((tar.y - start.y));
start = tar;
}
out.println(count);
}
out.close();
}
static class Node {
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
}