using System;
using System.Collections.Generic;
class Boggle
{
static int M = 3;
static int N = 3;
static bool dfs(char[][] board, string s, int i, int j, int n, int m, int idx)
{
if (i < 0 || i >= n || j < 0 || j >= m)
{
return false;
}
if (s[idx] != board[i][j])
{
return false;
}
if (idx == s.Length - 1)
{
return true;
}
char temp = board[i][j];
board[i][j] = '*';
bool a = dfs(board, s, i, j + 1, n, m, idx + 1);
bool b = dfs(board, s, i, j - 1, n, m, idx + 1);
bool c = dfs(board, s, i + 1, j, n, m, idx + 1);
bool d = dfs(board, s, i - 1, j, n, m, idx + 1);
bool e = dfs(board, s, i + 1, j + 1, n, m, idx + 1);
bool f = dfs(board, s, i - 1, j + 1, n, m, idx + 1);
bool g = dfs(board, s, i + 1, j - 1, n, m, idx + 1);
bool h = dfs(board, s, i - 1, j - 1, n, m, idx + 1);
board[i][j] = temp;
return a || b || c || e || f || g || h || d;
}
static void wordBoggle(char[][] board, string[] dictionary)
{
int n = board.Length;
int m = board[0].Length;
List<string> ans = new List<string>();
HashSet<string> store = new HashSet<string>();
for (int i = 0; i < dictionary.Length; i++)
{
string s = dictionary[i];
int l = s.Length;
for (int j = 0; j < n; j++)
{
for (int k = 0; k < m; k++)
{
if (dfs(board, s, j, k, n, m, 0))
{
store.Add(s);
}
}
}
}
foreach (string i in store)
{
Console.WriteLine(i);
}
return;
}
public static void Main()
{
char[][] boggle = new char[][] {
new char[] { 'G', 'I', 'Z' },
new char[] { 'U', 'E', 'K' },
new char[] { 'Q', 'S', 'E' }
};
string[] dictionary = new string[] {"GEEKS", "FOR", "QUIZ", "GO"};
Console.WriteLine("Following words of dictionary are present");
wordBoggle(boggle, dictionary);
}
}