forked from NiharRanjan53/HacktoberFest_2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCount of number of given string in 2D character array
94 lines (82 loc) · 1.84 KB
/
Count of number of given string in 2D character array
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
// C++ code for finding count
// of string in a given 2D
// character array.
#include <bits/stdc++.h>
using namespace std;
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a))
// utility function to search
// complete string from any
// given index of 2d char array
int internalSearch(string needle, int row,
int col, string hay[],
int row_max, int col_max, int xx)
{
int found = 0;
if (row >= 0 && row <= row_max && col >= 0 &&
col <= col_max && needle[xx] == hay[row][col])
{
char match = needle[xx];
xx += 1;
hay[row][col] = 0;
if (needle[xx] == 0)
{
found = 1;
}
else
{
// through Backtrack searching
// in every directions
found += internalSearch(needle, row,
col + 1, hay,
row_max, col_max,xx);
found += internalSearch(needle, row, col - 1,
hay, row_max, col_max,xx);
found += internalSearch(needle, row + 1, col,
hay, row_max, col_max,xx);
found += internalSearch(needle, row - 1, col,
hay, row_max, col_max,xx);
}
hay[row][col] = match;
}
return found;
}
// Function to search the string in 2d array
int searchString(string needle, int row, int col,
string str[], int row_count,
int col_count)
{
int found = 0;
int r, c;
for (r = 0; r < row_count; ++r)
{
for (c = 0; c < col_count; ++c)
{
found += internalSearch(needle, r, c, str,
row_count - 1,
col_count - 1, 0);
}
}
return found;
}
// Driver code
int main()
{
string needle = "MAGIC";
string input[] = { "BBABBM",
"CBMBBA",
"IBABBG",
"GOZBBI",
"ABBBBC",
"MCIGAM" };
string str[ARRAY_SIZE(input)];
int i;
for (i = 0; i < ARRAY_SIZE(input); ++i)
{
str[i] = input[i];
}
cout << "count: " << searchString(needle, 0, 0, str,
ARRAY_SIZE(str),
str[0].size()) << endl;
return 0;
}
// This code is contributed by SHUBHAMSINGH8410