Check if a word exists in a grid or not | C # program to check if the word exists in the grid or not ; Function to check if a word exists in a grid starting from the first match in the grid level : index till which pattern is matched x , y : current position in 2D array ; Pattern matched ; Out of Boundary ; If grid matches with a letter while recursion ; Marking this cell as visited ; finding subpattern in 4 directions ; marking this cell as unvisited again ; else Not matching then false ; Function to check if the word exists in the grid or not ; if total characters in matrix is less then pattern lenghth ; Traverse in the grid ; If first letter matches , then recur and check ; Driver Code ; Function to check if word exists or not
using System ; class GFG { static readonly int r = 4 ; static readonly int c = 4 ; static bool findmatch ( char [ , ] mat , String pat , int x , int y , int nrow , int ncol , int level ) { int l = pat . Length ; if ( level == l ) return true ; if ( x < 0 y < 0 x >= nrow y >= ncol ) return false ; if ( mat [ x , y ] == pat [ level ] ) { char temp = mat [ x , y ] ; mat [ x , y ] = ' # ' ; bool res = findmatch ( mat , pat , x - 1 , y , nrow , ncol , level + 1 ) | findmatch ( mat , pat , x + 1 , y , nrow , ncol , level + 1 ) | findmatch ( mat , pat , x , y - 1 , nrow , ncol , level + 1 ) | findmatch ( mat , pat , x , y + 1 , nrow , ncol , level + 1 ) ; mat [ x , y ] = temp ; return res ; } return false ; } static bool checkMatch ( char [ , ] mat , String pat , int nrow , int ncol ) { int l = pat . Length ; if ( l > nrow * ncol ) return false ; for ( int i = 0 ; i < nrow ; i ++ ) { for ( int j = 0 ; j < ncol ; j ++ ) { if ( mat [ i , j ] == pat [ 0 ] ) if ( findmatch ( mat , pat , i , j , nrow , ncol , 0 ) ) return true ; } } return false ; } public static void Main ( String [ ] args ) { char [ , ] grid = { { ' a ' , ' x ' , ' m ' , ' y ' } , { ' b ' , ' g ' , ' d ' , ' f ' } , { ' x ' , ' e ' , ' e ' , ' t ' } , { ' r ' , ' a ' , ' k ' , ' s ' } } ; if ( checkMatch ( grid , " geeks " , r , c ) ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }