using System;
using System.Collections.Generic;
class GfG {
// function to perform dfs on the grid
static void dfs(char[,] letters,
bool[,] visited,
int i, int j, string str,
HashSet<string> wordSet,
List<string> ans) {
// check if the current cell is out of bounds
if (i < 0 || i >= letters.GetLength(0) ||
j < 0 || j >= letters.GetLength(1)) {
return;
}
// check if the current cell is already visited
if (visited[i, j]) {
return;
}
// mark the current cell as visited
visited[i, j] = true;
// add the current character to the string
str += letters[i, j];
// check if the current string is in the wordSet
if (wordSet.Contains(str)) {
ans.Add(str);
// remove the word from the set to avoid duplicates
wordSet.Remove(str);
}
// perform dfs on all 8 directions
for (int row = -1; row <= 1; row++) {
for (int col = -1; col <= 1; col++) {
// skip the current cell
if (row == 0 && col == 0) continue;
dfs(letters, visited, i + row,
j + col, str, wordSet, ans);
}
}
// backtrack and unmark the current cell as visited
visited[i, j] = false;
// remove the last character from the string
str = str.Substring(0, str.Length - 1);
}
// find all words in a given grid of characters
// and a given dictionary
static List<string> findWords(List<string> words,
char[,] letters) {
int n = letters.GetLength(0), m = letters.GetLength(1);
List<string> ans = new List<string>();
// store the words in the hashSet
HashSet<string> wordSet = new HashSet<string>(words);
// to mark the cell visited
bool[,] visited = new bool[n, m];
// perform dfs on each cell of the grid
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
dfs(letters, visited, i, j, "", wordSet, ans);
}
}
return ans;
}
static void Main() {
List<string> words = new List<string>{"geeks", "for", "quiz", "go"};
char[,] letters = {
{'g', 'i', 'z'},
{'u', 'e', 'k'},
{'q', 's', 'e'}
};
List<string> ans = findWords(words, letters);
foreach (string word in ans) {
Console.Write(word + " ");
}
}
}