機器人初始位置在原點(0, 0),小伙伴事先給機器人輸入一串指令command,機器人就會無限回圈這條指令的步驟進行移動,指令有兩種:
U: 向y軸正方向移動一格
R: 向x軸正方向移動一格,
不幸的是,在 xy 平面上還有一些障礙物,他們的坐標用obstacles表示,機器人一旦碰到障礙物就會被損毀,
給定終點坐標(x, y),回傳機器人能否完好地到達終點,如果能,回傳true;否則回傳false,
輸入:command = "URR", obstacles = [], x = 3, y = 2
輸出:true
解釋:U(0, 1) -> R(1, 1) -> R(2, 1) -> U(2, 2) -> R(3, 2),
輸入:command = "URR", obstacles = [[2, 2]], x = 3, y = 2
輸出:false
解釋:機器人在到達終點前會碰到(2, 2)的障礙物,
輸入:command = "URR", obstacles = [[4, 2]], x = 3, y = 2
輸出:true
解釋:到達終點后,再碰到障礙物也不影響回傳結果,
class Solution {
public boolean robot(String command, int[][] obstacles, int x, int y) {
char[] c = command.toCharArray();
int xSteps = 0;
int ySteps = 0;
int[][] path = new int[c.length][2];
for (int i = 0; i < c.length; i++) {
switch (c[i]) {
case 'U':
ySteps++;
break;
case 'R':
xSteps++;
break;
}
path[i][0] = xSteps;
path[i][1] = ySteps;
}
for (int[] o : obstacles) {
if (o[0] >= x && o[1] >= y) {
continue;
}
if (check(path, o[0], o[1], xSteps, ySteps)) {
return false;
}
}
return check(path, x, y, xSteps, ySteps);
}
private static boolean check(int[][] path, int xo, int yo, int xSteps, int ySteps) {
for (int[] p : path) {
if (((xo - p[0]) % xSteps == 0 && (yo - p[1]) % ySteps == 0) && ((xo - p[0]) / xSteps == (yo - p[1]) / ySteps)) {
return true;
}
}
return false;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/225463.html
標籤:Java
下一篇:2020年最新Java學習路線
