본문 바로가기
  • Jetpack 알아보기
LeetCode/Easy

[Java] LeetCode 874 : Walking Robot Simulation

by 새우버거♬ 2021. 4. 17.

LeetCode # 874


 

 

Example 1:

 

Input:
commands = [4,-1,3], obstacles = []
Output:

25
Explanation:
The robot starts at (0, 0): 1. Move north 4 units to (0, 4). 2. Turn right. 3. Move east 3 units to (3, 4). The furthest point away from the origin is (3, 4), which is 32 + 42 = 25 units away.

 

 


 

Solution #1 (11ms)

import java.awt.*;
import java.util.HashSet;
import java.util.Set;

class Solution {
    int[] xStep = new int[]{0, 1, 0, -1};
    int[] yStep = new int[]{1, 0, -1, 0};

    int direction = 0, x = 0, y = 0;
    int result = 0;

    public int robotSim(int[] commands, int[][] obstacles) {
        Set<Point> set = new HashSet<>();
        for (int[] obs : obstacles) {
            set.add(new Point(obs[0], obs[1]));
        }

        for (int command : commands) {
            if (command == -1 || command == -2) {
                direction = getDirection(command);
            } else {
                for (int j = 0; j < command; j++) {
                    int xTmp = x + xStep[direction];
                    int yTmp = y + yStep[direction];
                    Point point = new Point(xTmp, yTmp);

                    if (set.contains(point)) {
                        break;
                    }

                    x = xTmp;
                    y = yTmp;
                }
            }
            result = Math.max(result, (x * x) + (y * y));
        }

        return result;
    }

    private int getDirection(int d) {
        if (d == -2) direction -= 1;
        else if (d == -1) direction += 1;

        return (direction < 0 ? (direction + 4) : direction) % 4;
    }
}

 

Result #1

 

 


 

More Algorithm!

 

👇👇

 

github.com/ggujangi/ggu.leet-code

 

ggujangi/ggu.leet-code

LeetCode, Java. Contribute to ggujangi/ggu.leet-code development by creating an account on GitHub.

github.com

 

 

 

 

출처 : leetCode