This question has 2 possible solutions and I am trying to implement the DFS solution.
Here is the Trie and DFS solution: Boggle using Trie and DFS
Please review for performance.
Given a dictionary, a method to do lookup in dictionary and a M x N board where every cell has one character. Find all possible words that can be formed by a sequence of adjacent characters. Note that we can move to any of 8 adjacent characters, but a word should not have multiple instances of same cell.
Example: Input: dictionary[] = {"GEEKS", "FOR", "QUIZ", "GO"}; boggle[][] = {{'G', 'I', 'Z'}, {'U', 'E', 'K'}, {'Q', 'S', 'E'}}; isWord(str): returns true if str is present in dictionary else false. Output: Following words of dictionary are present GEEKS QUIZ
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace GraphsQuestions
{
/// <summary>
/// https://www.geeksforgeeks.org/boggle-find-possible-words-board-characters/
/// </summary>
[TestClass]
public class BoggleDfs
{
private List<string> _list = new List<string>();
[TestMethod]
public void GeeksForGeeksTest()
{
string[] dictionary = { "GEEKS", "FOR", "QUIZ", "GO" };
char[,] boggle = {{'G', 'I', 'Z'},
{'U', 'E', 'K'},
{'Q', 'S', 'E'}};
FindWords(boggle, dictionary);
string[] expected = { "GEEKS", "QUIZ" };
CollectionAssert.AreEqual(expected,_list.ToArray());
}
private void FindWords(char[,] boggle, string[] dictionary)
{
bool[,] visited = new bool[boggle.GetLength(0), boggle.GetLength(1)];
StringBuilder str = new StringBuilder();
//run DFS for all the options and compare with the dictionary
for (int i = 0; i < boggle.GetLength(0); i++)
{
for (int j = 0; j < boggle.GetLength(1); j++)
{
DFS(i, j, boggle, dictionary, str, visited);
}
}
}
private void DFS(int i, int j, char[,] boggle, string[] dictionary, StringBuilder str, bool[,] visited)
{
//mark we already visited this vertex
visited[i, j] = true;
str.Append(boggle[i, j]);
if (IsWord(str.ToString(), dictionary))
{
_list.Add(str.ToString());
}
for (int row = i - 1; row <= i + 1 && row < boggle.GetLength(0); row++)
{
for (int col = j - 1; col <= j + 1 && col < boggle.GetLength(1); col++)
{
if (col >= 0 && row >= 0 && !visited[row, col])
{
DFS(row, col, boggle, dictionary, str, visited);
}
}
}
visited[i, j] = false;
str.Remove(str.Length - 1, 1);
}
private bool IsWord(string str, string[] dictionary)
{
for (int i = 0; i < dictionary.Length; i++)
{
if (string.CompareOrdinal(str, dictionary[i]) == 0)
{
return true;
}
}
return false;
}
}
}