> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/google/657-judge-route-circle.md).

# 657 Judge Route Circle

## 657. [Judge Route Circle](https://leetcode.com/problems/judge-route-circle/description/)

## 1. Question

Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to **the original place**.

The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are`R`(Right),`L`(Left),`U`(Up) and`D`(down). The output should be true or false representing whether the robot makes a circle.

**Example 1:**

```
Input: "UD"

Output: true
```

**Example 2:**

```
Input: "LL"

Output: false
```

## 2. Implementation

**(1) Intuition**

```java
class Solution {
    public boolean judgeCircle(String moves) {
        int horizontalMove = 0, verticalMove = 0;

        for (char move : moves.toCharArray()) {
            switch(move) {
                case 'U': 
                    --verticalMove;
                    break;
                case 'D': 
                    ++verticalMove;
                    break;
                case 'L': 
                    --horizontalMove;
                    break;
                case 'R': 
                    ++horizontalMove;
                    break;
            }
        }

        return horizontalMove == 0 && verticalMove == 0;
    }
}
```

**(2) HashMap**

```java
class Solution {
    public boolean judgeCircle(String moves) {
        Map<Character, Integer> map = new HashMap<>();

        map.put('U', -1);
        map.put('D', 1);
        map.put('L', -2);
        map.put('R', 2);

        int offset = 0;

        for (char c : moves.toCharArray()) {
            offset += map.get(c);
        }

        return offset == 0;
    }
}
```

## 3. Time & Space Complexity

**Intuition:** 时间复杂度O(n), 空间复杂度O(1)

**HashMap:** 时间复杂度O(n), 空间复杂度O(n)
