阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
问题描述: 给定一个 width x height 的网格,机器人初始位置在 (0, 0),朝向东。机器人按指令前进指定步数,规则如下:
需要实现三个方法:
Robot(int width, int height):初始化网格与机器人;void step(int num):前进 num 步;int[] getPos():返回当前位置 [x, y];String getDir():返回当前方向。示例:
输入: ["Robot", "step", "step", "getPos", "getDir", "step", "step", "step", "getPos", "getDir"] [[6, 3], [2], [2], [], [], [2], [1], [4], [], []] 输出: [null, null, null, [4, 0], "East", null, null, null, [1, 2], "West"]
2 × (width-1 + height-1);num 很大时,直接模拟会超时,可先对一圈长度取模,仅需走余数步;(0,0) 时,方向为南。perimeter = 2 × (width-1 + height-1);num %= perimeter,消除重复绕圈;(0,0),强制方向为南;package com.sheeta1998.lec.lc2069;
public class Robot {
int width = 0;
int height = 0;
int x = 0;
int y = 0;
int direction = 1;//1为东,2为北,3为西,4为南
public Robot(int width, int height) {
this.width = width;
this.height = height;
}
public void step(int num) {
int perimeter = 2 * ((width - 1) + (height - 1));
if (perimeter == 0) return;
if ((num % perimeter) == 0 && x == 0 && y == 0) {
direction = 4;
}
num %= perimeter;
for (int i = 0; i < num; i++) {
if (direction == 1) {
if (x < width - 1) {
x += 1;
} else {
direction += 1;
y += 1;
}
} else if (direction == 2) {
if (y < height - 1) {
y += 1;
} else {
direction += 1;
x -= 1;
}
} else if (direction == 3) {
if (x > 0) {
x -= 1;
} else {
direction += 1;
y -= 1;
}
} else {
if (y > 0) {
y -= 1;
} else {
direction = 1;
x += 1;
}
}
}
}
public int[] getPos() {
int[] res = {x, y};
return res;
}
public String getDir() {
String res;
if (direction == 1) {
res = "East";
} else if (direction == 2) {
res = "North";
} else if (direction == 3) {
res = "West";
} else {
res = "South";
}
return res;
}
}将环形周长提取为变量,代码更清晰、不易出错。
增加边界判断,避免宽/高为 1 时除零错误。
使用数组映射方向数字与字符串,消除冗长 if-else:
private final String[] dirStr = {"East", "North", "West", "South"};时间复杂度:
空间复杂度:
(0,0) 且步数走完一圈时,方向为南;(0,0) 满圈后方向为南;