-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortestPath.java
More file actions
39 lines (30 loc) · 936 Bytes
/
Copy pathShortestPath.java
File metadata and controls
39 lines (30 loc) · 936 Bytes
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
package strings;
public class ShortestPath {
public static float shortestPath(String path) {
int x = 0, y = 0;
for (int i = 0; i < path.length(); i++) {
char direction = path.charAt(i);
if(direction == 'S') { // south
y--;
} else if (direction == 'N') { // north
y++;
} else if ( direction == 'W') { // west
x--;
} else { // east
x++;
}
}
int X2 = x * x;
int Y2 = y * y;
return (float)Math.sqrt(X2 + Y2);
}
public static void main(String[] args) {
String path = "WNEENESENNN";
System.out.println(shortestPath(path));
}
}
/*
Given a route containing 4 directions (E, W, N, S), find the shortest path (straight-line distance) to reach the destination from the origin.
Example:
Input: "WNEENESENNN"
Output: 5.0 */