I have been trying to debug this code but now really need help at this point. It is the code for finding a string in a grid but due to some reason I'm getting segmentation fault.Any pointers would be highly appreciated
#include <stdio.h>
char grid[5][5] = {
{'t', 'z', 'x', 'c', 'd'},
{'a', 'h', 'n', 'z', 'x'},
{'h', 'w', 'o', 'i', 'o'},
{'o', 'r', 'n', 'r', 'n'},
{'a', 'b', 'r', 'i', 'n'},
};
int n = 5;
int found = 0; // flag indicating if string has been found
void find(int i, int j, char *search) {
if (i >= n || j >= n || i < 0 || j < 0) {
return ;
}
if (!search) {
found = 1;
return ;
}
if (grid[i][j] == search[0]) {
find (i+1, j, search+1);
find (i, j+1, search+1);
find (i+1, j+1, search+1);
find (i-1, j, search+1);
find (i, j-1, search+1);
find (i-1, j-1, search+1);
}
else {
find (i+1, j, search);
find (i, j+1, search);
find (i+1, j+1, search);
find (i-1, j, search);
find (i, j-1, search);
find (i-1, j-1, search);
}
}
int main() {
char s[] = {'h', 'o', 'r', 'i', 'z', 'o', 'n', '\0'}; // String to be searched
find(0, 0, s);
printf("%s\n", found ? "Found": "Not Found");
return 0;
}
The problem with your implementation is that you haven't written the recursion properly. For continuous path search you shouldn't look at the neighbors if the character doesn't match.
Also second mistake you made is expecting search
to become NULL when string finishes. Infact you need to check if search[0] =='\0'
.
Since you don't look at the neighbors(by removing the else), you need to look at all starting points.
Consider the following code.
#include <stdio.h>
char grid[5][5] = {
{'t', 'z', 'x', 'c', 'd'},
{'a', 'h', 'n', 'z', 'x'},
{'h', 'w', 'o', 'i', 'o'},
{'o', 'r', 'n', 'r', 'n'},
{'a', 'b', 'r', 'i', 'n'},
};
int n = 5;
int found = 0; // flag indicating if string has been found
void find(int i, int j, char *search) {
if (i >= n || j >= n || i < 0 || j < 0) {
return ;
}
if (search[0]=='\0') {
found = 1;
return ;
}
if (grid[i][j] == search[0]) {
find (i+1, j, search+1);
find (i, j+1, search+1);
find (i+1, j+1, search+1);
find (i-1, j, search+1);
find (i, j-1, search+1);
find (i-1, j-1, search+1);
}
}
int main() {
char s[] = {'h', 'o', 'r', 'i', 'z', 'o', 'n', '\0'}; // String to be searched
int i, j;
for(i = 0; i<n && !found;i++)
for(j = 0; j<n && !found;j++){
find(i, j, s);
}
printf("%s\n", found ? "Found": "Not Found");
return 0;
}
This works correctly and prints Found
.
Demo here : https://ideone.com/l3ohwr