-
Notifications
You must be signed in to change notification settings - Fork 5
/
JudgeRouteCircle.java
executable file
·79 lines (75 loc) · 2.37 KB
/
JudgeRouteCircle.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
Problem Statement:
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.
Problem Link:
Judge Route Circle: https://leetcode.com/problems/judge-route-circle/description/
Solution:
https://github.com/sunnypatel165/leetcode-again/blob/master/solutions/JudgeRouteCircle.java
Author:
Sunny Patel
https://github.com/sunnypatel165
https://www.linkedin.com/in/sunnypatel165/
*/
class Solution {
/**
* Method to move the point in the given direction
* @param point [Point to be moved]
* @param direction [Direction in which Point is to be moved]
* @return [Final position of the moved point]
*/
public Point move(Point point, char direction){
if(point == null || (direction!='U' && direction!='D' && direction!='L' && direction!='R'))
return point;
switch (direction){
case 'U':
point.setY(point.getY()+1);
break;
case 'D':
point.setY(point.getY()-1);
break;
case 'L':
point.setX(point.getX()-1);
break;
case 'R':
point.setX(point.getX()+1);
}
return point;
}
/**
* [judgeCircle description]
* @param moves [String representing moves]
* @return [If the moves lead to a circle or not.]
*/
public boolean judgeCircle(String moves) {
Point point = new Point(0,0);
for(int i=0;i<moves.length();i++){
point = move(point, moves.charAt(i));
}
return point.isOrigin();
}
}
class Point{
private int x;
private int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public boolean isOrigin(){
return this.getX()==0 && this.getY()==0;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public void setX(int x){
this.x=x;
}
public void setY(int y){
this.y=y;
}
}