高级农民
- 积分
- 1270
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-11-15
- 最后登录
- 1970-1-1
|
以下是我写的代码
package googl;
/**
* Created by Administrator on 4/19/2018.
* 0. 无论如何都需要有 direction, 顺时针 0 - 1 - 2 - 3, 增加为每次 turnRight,
* 1.机器人改变 direction 实际上对应的是 若干个 turnleft / turnRight, 所以 要有个一个 changeToDirection(int from, int to), 里面包若干个 turnleft/ turnRight
* 2.函数 return 时,机器人要 return回上一个点 -- > 沿进入该点的方向 之反方向 preDir -- preDir + 2, (或两次 turnright) 走一个 move,并返回到 进入改点的方向, 比如保持return的时候 其方向和原来的方向一致 同时回到原来的方向
* 3.本版本 是机器人内部保存 direction. x, y position 版本,默认 0 - direction为放置 机器人时 的初始 direction,房间可以颠倒过来看,怎样
*/
public class IRobot_9001 {. 1point 3acres
Robot robot;
int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
int direction;
/*不必保留 当前 posX, posY的位置,位置信息只在检查下一点是否可行时有用,DFS 中带入即可*/
public void sweep(int[][] map, int[] start) {
this.robot = new Robot();
boolean[][] visited = new boolean[map.length + 1][map[0].length + 1];
dfs(start[0], start[1], visited);
}
public void changeDirectionTo(int direction) {
/*clockwise turn -- > direction increases*/
if (direction == this.direction) return; // 不用改
int delta = direction - this.direction > 0 ? direction - this.direction : direction - this.direction + 4;
for (int i = 0; i < delta; i++) {
robot.turnRight();
}
. Χ this.direction = direction;
}
public void moveBack() {
changeDirectionTo(this.direction + 2);
robot.move();
changeDirectionTo(this.direction + 2);
}
public void dfs(int x, int y, boolean[][] visited) {
robot.clean(); // 成功进入 x,y 扫地
/*首先保存原有方向,便于退出时恢复*/
int prevDirection = this.direction;
/*有四个方向可选,当前方向继续 + 向右转 1, 2, 3 次
* 其中向右转2次相当于回退,由于 visited 必然标记为访问过,则必定不成功*/
/*下一步未访问过,且下一步访问成功*/
for (int i = 0; i < 4; i++) {
int nextX = x + dirs[i][0];. .и
int nextY = y + dirs[i][1];
changeDirectionTo(this.direction + 1); // 转向
if (!visited[nextX][nextY]) {
visited[nextX][nextY] = true;
/*不可移动的就跳下一轮循环*/
if (robot.move()) {
/*可以挪到下一个,在下一个继续 DFS, 注意此时进入下一层 DFS 的是新的 direction*/
dfs(nextX, nextY, visited);
}
}
}. .и
changeDirectionTo(prevDirection); // 重要,恢复成原来进入该格子时候的 方向,再做 moveback
moveBack(); // moveback里 两次转向保证了退回上一格仍然是进入该格子的方向
}
}
class Robot {
boolean move() {.1point3acres
/*Default method by moving one step on the current direction.google и
* will return true if move successfully*/
return true;
}
void turnLeft() {.google и
/*change direction to +90*/
}
. Waral dи,
void turnRight() {
/*change direction to -90*/
}
void clean() {
/*Do clean*/
}
}
|
|