179.Walking Robot Simulation

题目:

A robot on an infinite grid starts at point (0, 0) and faces north.  The robot can receive one of three possible types of commands:

无限网格上的机器人从点(0,0)开始并朝北。 机器人可以接收三种可能类型的命令之一:

  • -2: turn left 90 degrees      向左转90度
  • -1: turn right 90 degrees      向右转90度
  • 1 <= x <= 9: move forward x units    向前移动x个单位

Some of the grid squares are obstacles.    一些网格方块是障碍物

The i-th obstacle is at grid point (obstacles[i][0], obstacles[i][1])  第i个障碍位于网格点(obstacles[i] [0],obstacles[i] [1])

If the robot would try to move onto them, the robot stays on the previous grid square instead (but still continues following the rest of the route.)如果机器人试图移动它们,机器人将停留在前一个网格方格上(但仍然继续跟随其余路线。)

Return the square of the maximum Euclidean distance that the robot will be from the origin.返回机器人从原点开始的最大欧氏距离的平方。

Example 1:

Input: commands = [4,-1,3], obstacles = []
Output: 25
Explanation: robot will go to (3, 4)

Example 2:

Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
Output: 65
Explanation: robot will be stuck at (1, 4) before turning left and going to (1, 8)

 

Note:

  1. 0 <= commands.length <= 10000
  2. 0 <= obstacles.length <= 10000
  3. -30000 <= obstacle[i][0] <= 30000
  4. -30000 <= obstacle[i][1] <= 30000
  5. The answer is guaranteed to be less than 2 ^ 31.

解答:

 

 1 class Solution {
 2     public int robotSim(int[] commands, int[][] obstacles) {
 3         Set<String> set=new HashSet<>();
 4         for(int[] obs:obstacles)
 5             set.add(obs[0]+" "+obs[1]);
 6         
 7         int[][] dirs=new int[][]{{0,1},{1,0},{0,-1},{-1,0}};
 8         
 9         int d=0,x=0,y=0,res=0;  //d表示向右转90度的个数
10         for(int c:commands){
11             if(c==-1){
12                 d++;
13                 if(d==4)
14                     d=0;
15             }else if(c==-2){
16                 d--;
17                 if(d==-1)  //d向左转90度就相当于向右转3个90度
18                     d=3;
19             }else{
20                 while(c-->0 && !set.contains((x+dirs[d][0])+" "+(y+dirs[d][1]))){
21                     x+=dirs[d][0];
22                     y+=dirs[d][1];
23                 }
24             }
25             res=Math.max(res,x*x+y*y);
26         }
27         return res;
28     }
29 }

详解:

 

posted @ 2018-09-20 11:07  chan_ai_chao  阅读(274)  评论(0编辑  收藏  举报