#include <iostream>
#include <vector>
#include <string>
// use a depth‑first search (DFS) from every cell that matches the first letter,
// exploring all valid directions until the full word is matched.
using std::vector;
// DFS helper
bool dfs(vector<vector<char>>& grid, int r, int c, const std::string& word, int index) {
if (index == word.size())
return true;
int rows = grid.size();
int cols = grid[0].size();
if (r < 0 || c < 0 || r >= rows || c >= cols)
return false;
if (grid[r][c] != word[index])
return false;
char temp = grid[r][c];
grid[r][c] = '#'; // mark visited
bool found =
dfs(grid, r + 1, c, word, index + 1) ||
dfs(grid, r - 1, c, word, index + 1) ||
dfs(grid, r, c + 1, word, index + 1) ||
dfs(grid, r, c - 1, word, index + 1);
grid[r][c] = temp; // restore
return found;
}
// Main search function
bool wordExist(vector<vector<char>>& grid, const std::string& word) {
int rows = grid.size();
int cols = grid[0].size();
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (dfs(grid, r, c, word, 0))
return true;
}
}
return false;
}
int main() {
vector<vector<char>> grid = {
{'a', 'b', 'c', 'e'},
{'s', 'f', 'c', 's'},
{'a', 'd', 'e', 'e'}
};
std::string word = "see";
bool result = wordExist(grid, word);
std::cout << result; // prints 1 if found, 0 if not
}
/*
run:
1
*/