Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by
path.
Return trueif the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false
otherwise.
Input: path ="NES"Output: falseExplanation: Notice that the path doesn't cross any point more than once.
Input: path ="NESWW"Output: trueExplanation: Notice that the path visits the origin twice.
We simulate the walk on the 2D grid, keeping track of all visited positions in a set. If we ever visit a position we’ve already seen, the path crosses itself.
import java.util.*;
classSolution {
publicbooleanisPathCrossing(String path) {
Set<String> seen =new HashSet<>();
int x = 0, y = 0;
seen.add("0,0");
for (char c : path.toCharArray()) {
if (c =='N') y++;
elseif (c =='S') y--;
elseif (c =='E') x++;
elseif (c =='W') x--;
String key = x +","+ y;
if (seen.contains(key)) returntrue;
seen.add(key);
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
funisPathCrossing(path: String): Boolean {
val seen = mutableSetOf<Pair<Int, Int>>()
var x = 0; var y = 0 seen.add(0 to 0)
for (c in path) {
when (c) {
'N'-> y++'S'-> y--'E'-> x++'W'-> x-- }
val pos = x to y
if (!seen.add(pos)) returntrue }
returnfalse}
1
2
3
4
5
6
7
8
9
10
11
12
13
defisPathCrossing(path: str) -> bool:
seen = set()
x = y =0 seen.add((0, 0))
for c in path:
if c =='N': y +=1elif c =='S': y -=1elif c =='E': x +=1elif c =='W': x -=1if (x, y) in seen:
returnTrue seen.add((x, y))
returnFalse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use std::collections::HashSet;
pubfnis_path_crossing(path: String) -> bool {
letmut seen = HashSet::new();
let (mut x, mut y) = (0, 0);
seen.insert((x, y));
for c in path.chars() {
match c {
'N'=> y +=1,
'S'=> y -=1,
'E'=> x +=1,
'W'=> x -=1,
_ => {}
}
if!seen.insert((x, y)) { returntrue; }
}
false}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
functionisPathCrossing(path: string):boolean {
constseen=newSet<string>();
letx=0, y=0;
seen.add('0,0');
for (constcofpath) {
if (c==='N') y++;
elseif (c==='S') y--;
elseif (c==='E') x++;
elseif (c==='W') x--;
constkey=`${x},${y}`;
if (seen.has(key)) returntrue;
seen.add(key);
}
returnfalse;
}