1496. Determine whether the path intersects
Give you a string path, where the value of path[i] can be'N','S','E' or'W', which means to move one unit to the north, south, east, and west respectively.
The robot starts from the origin (0, 0) on the two-dimensional plane and walks along the path indicated by path.
If the path intersects at any position, that is, if you go to a position that you have walked before, please return True; otherwise, return False.
提示:
1 <= path.length <= 10^4
path 仅由 {'N', 'S', 'E', 'W} 中的字符组成
answer:
We only need to create a point set set to store the point position after each movement, and then move the coordinates on the NSWE respectively, that is, assign a value to the point set set. After each "movement", it is necessary to judge whether they intersect.
Code:
bool isPathCrossing(char * path){
int x[10000] = {
0};
int y[10000] = {
0};
int t1 = 1;
for(int i=0;i<strlen(path);i++)
{
if(path[i]=='N')
{
x[t1] = x[t1-1];
y[t1] = y[t1-1];
y[t1++]++;
}
if(path[i]=='S')
{
x[t1] = x[t1-1];
y[t1] = y[t1-1];
y[t1++]--;
}
if(path[i]=='W')
{
y[t1] = y[t1-1];
x[t1] = x[t1-1];
x[t1++]--;
}
if(path[i]=='E')
{
x[t1] = x[t1-1];
y[t1] = y[t1-1];
x[t1++]++;
}
for(int j=0;j<t1-1;j++)
{
if(x[j]==x[t1-1]&&y[j]==y[t1-1])
{
return 1;
}
}
}
return 0;
}