📣 Back to School开学季 - VIP通行证5折优惠!蓝莓、Offer多多同步优惠
123
返回列表 发新帖
楼主: Soap.cmu
跳转到指定楼层
上一主题 下一主题
收起左侧

Pocket Gems 两轮电面.

全局:
  1. import java.util.*;

  2. class Main {
  3.   public static void main(String[] args) {
  4.     Robot r = new Robot();
  5.     char[][] maze = {
  6.       {'T', 'T', 'T', 'F'},
  7.       {'F', 'T', 'F', 'T'},
  8.       {'F', 'T', 'T', 'T'}
  9.     };
  10.     List<String> res = r.findPath(maze, 1, 1);
  11.     System.out.println(String.join(" ", res));
  12.   }
  13. }

  14. class Robot {
  15.   private List<String> path;
  16.   private final Map<Integer, String> dirMap;
  17.   private int count;
  18.   Robot() {
  19.     this.dirMap = new HashMap<>();
  20.     dirMap.put(0, "up");
  21.     dirMap.put(1, "right");
  22.     dirMap.put(2, "down");
  23.     dirMap.put(3, "left");
  24.   }
  25.   public List<String> findPath(char[][] maze, int x, int y) {
  26.     path = null;
  27.     int m = maze.length;
  28.     int n = maze[0].length;
  29.     count = 0;
  30.     for (int i = 0; i < m; i++) {
  31.       for (int j = 0; j < n; j++) {
  32.         if (maze[i][j] == 'T') {
  33.           count++;
  34.         }
  35.       }
  36.     }
  37.    
  38.     boolean[][] visited = new boolean[m][n];
  39.     dfs(maze, x, y, visited, new ArrayList<>(), -1);
  40.    
  41.     return path == null ? new ArrayList<String>() : path;
  42.   }
  43.   
  44.   private void dfs(char[][] maze, int x, int y, boolean[][] visited, List<String> curPath, int comingDirection) {
  45.     int m = maze.length;
  46.     int n = maze[0].length;
  47.     visited[x][y] = true;
  48.     count--;
  49.    
  50.     if (count == 0) {
  51.       if (path == null) {
  52.         path = curPath;
  53.       }
  54.       return;
  55.     }
  56.    
  57.     int[][] dirs = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } };
  58.     for (int i = 0; i < 4; i++) {
  59.       int xx = x + dirs[i][0];
  60.       int yy = y + dirs[i][1];
  61.       
  62.       if (xx < 0 || xx >= m || yy < 0 || yy >= n || visited[xx][yy] || maze[xx][yy] == 'F') {
  63.         continue;
  64.       }
  65.       curPath.add(dirMap.get(i));
  66.       dfs(maze, xx, yy, visited, curPath, i);
  67.     }
  68.    
  69.     if (comingDirection != -1 && path == null) {
  70.       curPath.add(dirMap.get((comingDirection + 2) % 4));
  71.     }
  72.   }
  73. }
复制代码
贴个解法https://repl.it/JkZ4/2

补充内容 (2017-7-26 20:44):
大概思路就是纯dfs,记录每次所到点来的方向,在每个路口所有4个方向走完返回前,把一个反方向加到路径里(L71-73)
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表