Check if a given string can be formed using characters of adjacent cells of a Matrix | C # program to check if a given word can be formed from the adjacent characters in a matrix of characters ; Function to check if the word exists ; If index exceeds board range ; If the current cell does not contain the required character ; If the cell contains the required character and is the last character of the word required to be matched ; Return true as word is found ; Mark cell visited ; Check adjacent cells for the next character ; Restore cell value ; Driver Code
using System ; class GFG { static bool checkWord ( char [ , ] board , String word , int index , int row , int col ) { if ( row < 0 || col < 0 || row >= board . GetLength ( 0 ) || col >= board . GetLength ( 1 ) ) return false ; if ( board [ row , col ] != word [ index ] ) return false ; else if ( index == word . Length - 1 ) return true ; char temp = board [ row , col ] ; board [ row , col ] = ' * ' ; 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 ; } board [ row , col ] = temp ; return false ; } 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 " ) ; } }