-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath_crossing.c
96 lines (89 loc) · 2.26 KB
/
path_crossing.c
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Linked list
struct Node {
int id;
struct Node* next;
};
bool search(struct Node* root, int target) {
struct Node* curr = root;
while (curr != NULL) {
if (curr->id == target)
return true;
curr = curr->next;
}
return false;
}
bool isPathCrossing(char * path){
int range = 2 * strlen(path) + 1;
int x = strlen(path);
int y = strlen(path);
// Log 0,0
struct Node* history = (struct Node*) malloc(sizeof(struct Node));
history->id = x * range + y; history->next = NULL;
struct Node* last = history;
for (int i = 0; i < strlen(path); i++) {
// Calculate navigation
switch(path[i]) {
case 'N':
y++;
break;
case 'S':
y--;
break;
case 'E':
x++;
break;
case 'W':
x--;
break;
default:
break;
}
// Check history
if (!search(history, x*range+y)) {
last->next = (struct Node*) malloc(sizeof(struct Node));
last->next->id = x*range+y; last->next->next = NULL;
last = last->next;
} else {
return true;
}
}
return false;
}
// Memory Intensive Solution
/*
bool isPathCrossing(char * path){
// History is a 2D -> 1D boolean array
int range = 2 * strlen(path) + 1;
bool* history = (bool*) malloc(range * range * sizeof(bool));
memset(history, false, range * range * sizeof(bool));
int x = strlen(path);
int y = strlen(path);
// Log 0,0
history[x*range + y] = true;
for (int i = 0; i < strlen(path); i++) {
// Calculate navigation
switch(path[i]) {
case 'N':
y++;
break;
case 'S':
y--;
break;
case 'E':
x++;
break;
case 'W':
x--;
break;
default:
break;
}
// Check history
if (!history[x*range + y]) {
history[x*range + y] = true;
} else {
return true;
}
}
return false;
} */