高级农民
- 积分
- 2595
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-3-10
- 最后登录
- 1970-1-1
|
- import java.util.*;
- class Main {
- public static void main(String[] args) {
- Robot r = new Robot();
- char[][] maze = {
- {'T', 'T', 'T', 'F'},
- {'F', 'T', 'F', 'T'},
- {'F', 'T', 'T', 'T'}
- };
- List<String> res = r.findPath(maze, 1, 1);
- System.out.println(String.join(" ", res));
- }
- }
- class Robot {
- private List<String> path;
- private final Map<Integer, String> dirMap;
- private int count;
- Robot() {
- this.dirMap = new HashMap<>();
- dirMap.put(0, "up");
- dirMap.put(1, "right");
- dirMap.put(2, "down");
- dirMap.put(3, "left");
- }
- public List<String> findPath(char[][] maze, int x, int y) {
- path = null;
- int m = maze.length;
- int n = maze[0].length;
- count = 0;
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < n; j++) {
- if (maze[i][j] == 'T') {
- count++;
- }
- }
- }
-
- boolean[][] visited = new boolean[m][n];
- dfs(maze, x, y, visited, new ArrayList<>(), -1);
-
- return path == null ? new ArrayList<String>() : path;
- }
-
- private void dfs(char[][] maze, int x, int y, boolean[][] visited, List<String> curPath, int comingDirection) {
- int m = maze.length;
- int n = maze[0].length;
- visited[x][y] = true;
- count--;
-
- if (count == 0) {
- if (path == null) {
- path = curPath;
- }
- return;
- }
-
- int[][] dirs = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } };
- for (int i = 0; i < 4; i++) {
- int xx = x + dirs[i][0];
- int yy = y + dirs[i][1];
-
- if (xx < 0 || xx >= m || yy < 0 || yy >= n || visited[xx][yy] || maze[xx][yy] == 'F') {
- continue;
- }
- curPath.add(dirMap.get(i));
- dfs(maze, xx, yy, visited, curPath, i);
- }
-
- if (comingDirection != -1 && path == null) {
- curPath.add(dirMap.get((comingDirection + 2) % 4));
- }
- }
- }
复制代码 贴个解法https://repl.it/JkZ4/2
补充内容 (2017-7-26 20:44):
大概思路就是纯dfs,记录每次所到点来的方向,在每个路口所有4个方向走完返回前,把一个反方向加到路径里(L71-73) |
|