Check if a given string can be formed using characters of adjacent cells of a Matrix | Java 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
import java . util . * ; class GFG { static boolean checkWord ( char [ ] [ ] board , String word , int index , int row , int col ) { if ( row < 0 col < 0 row >= board . length col >= board [ 0 ] . length ) return false ; if ( board [ row ] [ col ] != word . charAt ( 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 . length ; i ++ ) { for ( int j = 0 ; j < board [ 0 ] . length ; j ++ ) { if ( board [ i ] [ j ] == word . charAt ( 0 ) && checkWord ( board , word , 0 , i , j ) ) { System . out . println ( " True " ) ; return ; } } } System . out . println ( " False " ) ; } }