1496. 判断路径是否相交-哈希表法
给你一个字符串 path,其中 path[i] 的值可以是 ‘N’、‘S’、‘E’ 或者 ‘W’,分别表示向北、向南、向东、向西移动一个单位。
你从二维平面上的原点 (0, 0) 处开始出发,按 path 所指示的路径行走。
如果路径在任何位置上与自身相交,也就是走到之前已经走过的位置,请返回 true ;否则,返回 false 。
示例 1:
输入:path = “NES”
输出:false
解释:该路径没有在任何位置相交。
示例 2:
输入:path = “NESWW”
输出:true
解释:该路径经过原点两次。
这题用哈希表去做是很不错的,解题代码如下:
#define size 10000
struct hash{
struct hash *next;
int x;
int y;
};
void add_hash(struct hash* h,int x,int y){
struct hash*p=(struct hash *)malloc(sizeof(struct hash ));
p->x=x;
p->y=y;
p->next=h->next;
h->next=p;
}
bool find_hash(struct hash *h,int x,int y){
struct hash*p=h->next;
while(p){
if(p->y==y&&p->x==x){
return true;
}
p=p->next;
}
return false;
}
bool isPathCrossing(char * path){
struct hash *h=(struct hash *)malloc(sizeof(struct hash )*size);
for(int i=0;i<size;i++){
(h+i)->next=NULL;
}
int x=0,y=0;
add_hash(h+0%size,0,0);
for(int i=0;path[i]!='\0';i++){
char ch=path[i];
if(ch=='N'){
y=y+1;
}
else if(ch=='S'){
y=y-1;
}
else if(ch=='E'){
x=x+1;
}
else if(ch=='W'){
x=x-1;
}
// printf("%d %d ",x,y);
if(find_hash(h+abs(x)%size,x,y)){
return true;
}
add_hash(h+abs(x)%size,x,y);
}
return false;
}