Recursion : Program to search a word in a given 2 dimensional matrix of letters
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<cstring>
using namespace std;
class WordSearch {
public:
bool Search (int r, int c, int height, int width, string& word, vector<string>& board, int sz) {
// If the word size has reached the size of the word that we are looking for
if (sz == word.size()) return true;
// If the current search position goes beyond the board size or there is a character mismatch
if (r < 0 || c < 0 || r == height || c == width || board[r][c] != word[sz]) return false;
// Hash out the visited position as we don't want to visit it again
char ch = board[r][c];
board[r][c] = '#';
int left = Search (r-1, c, height, width, word, board, sz+1);
int right = Search (r+1, c, height, width, word, board, sz+1);
int up = Search (r, c+1, height, width, word, board, sz+1);
int down = Search (r, c-1, height, width, word, board, sz+1);
// Revert the modified character.
board[r][c] = ch;
return left || right || up || down;
}
// Below function returns true if the word [word] exist on the board
bool Exist (vector<string> board, string word) {
int rows = board.size();
int cols = board[0].size();
for (int r=0; r<rows; r++) {
for (int c=0; c<cols; c++) {
// Start search only if the 1'st characters of the word matches
if (board[r][c] == word[0]) {
if (Search (r, c, rows, cols, word, board, 0)) return true;
}
}
}
return false;
}
};
int main() {
WordSearch W;
//====================================
vector<string> vec_1 = {{"ABCE"},
{"SFCS"},
{"ADEE"}};
if (W.Exist(vec_1, "ABCCED") == 1)
cout << "Yes" << endl;
else
cout << "No" << endl;
//====================================
vector<string> vec_2 = {{"AAAAA"},
{"AAAAA"},
{"AAAAA"},
{"AAAAA"}};
if (W.Exist(vec_2, "AAB") == 1)
cout << "Yes" << endl;
else
cout << "No" << endl;
//====================================
vector<string> vec_3 = {{"FGABG"},
{"EFAEC"},
{"GGFBD"},
{"GGDCD"}};
if (W.Exist(vec_3, "FEGGGDCDDCGBAG") == 1)
cout << "Yes" << endl;
else
cout << "No" << endl;
//====================================
vector<string> vec_4 = {{"FCDFFD"},
{"BGCBFC"}};
if (W.Exist(vec_4, "FBGCDCBFFF") == 1)
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
Output
Yes
No
Yes
Yes
© 2019-2026 Algotree.org | All rights reserved.
This content is provided for educational purposes. Feel free to learn, practice, and share knowledge.
For questions or contributions, visit algotree.org
"Java is to JavaScript what car is to carpet. - Chris Heilmann"