// C# program to check if a given word
// can be formed from the adjacent
// characters in a matrix of characters
using System;
class GFG{
// Function to check if the word exists
static bool checkWord(char [,]board, String word,
int index, int row, int col)
{
// If index exceeds board range
if (row < 0 || col < 0 ||
row >= board.GetLength(0) ||
col >= board.GetLength(1))
return false;
// If the current cell does not
// contain the required character
if (board[row, col] != word[index])
return false;
// If the cell contains the required
// character and is the last character
// of the word required to be matched
else if (index == word.Length - 1)
// Return true as word is found
return true;
char temp = board[row, col];
// Mark cell visited
board[row, col] = '*';
// Check adjacent cells
// for the next character
if (checkWord(board, word,
index + 1, row + 1, col) ||
checkWord(board, word,
index + 1, row - 1, col) ||
checkWord(board, word,
index + 1, row, col + 1) ||
checkWord(board, word,
index + 1, row, col - 1))
{
board[row, col] = temp;
return true;
}
// Restore cell value
board[row, col] = temp;
return false;
}
// Driver Code
public static void Main(String[] args)
{
char[,] board = { { 'A', 'B', 'C', 'E' },
{ 'S', 'F', 'C', 'S' },
{ 'A', 'D', 'E', 'E' } };
String word = "CFDASABCESEE";
for(int i = 0; i < board.GetLength(0); i++)
{
for(int j = 0; j < board.GetLength(1); j++)
{
if (board[i, j] == word[0] &&
checkWord(board, word, 0, i, j))
{
Console.WriteLine("True");
return;
}
}
}
Console.WriteLine("False");
}
}
// This code is contributed by Rajput-Ji