Find all occurrences of a given word in a matrix | Javascript Program to find all occurrences of the word in a matrix ; check whether given cell ( row , col ) is a valid cell or not . ; return true if row number and column number is in range ; These arrays are used to get row and column numbers of 8 neighboursof a given cell ; A utility function to do DFS for a 2D boolean matrix . It only considers the 8 neighbours as adjacent vertices ; return if current character doesn 't match with  the next character in the word ; append current character position to path ; current character matches with the last character in the word ; Recur for all connected neighbours ; The main function to find all occurrences of the word in a matrix ; traverse through the all cells of given matrix ; occurrence of first character in matrix ; check and print if path exists ; Driver code
let ROW = 3 ; let COL = 5 ; function isvalid ( row , col , prevRow , prevCol ) { return ( row >= 0 ) && ( row < ROW ) && ( col >= 0 ) && ( col < COL ) && ! ( row == prevRow && col == prevCol ) ; } let rowNum = [ - 1 , - 1 , - 1 , 0 , 0 , 1 , 1 , 1 ] ; let colNum = [ - 1 , 0 , 1 , - 1 , 1 , - 1 , 0 , 1 ] ; function DFS ( mat , row , col , prevRow , prevCol , word , path , index , n ) { if ( index > n mat [ row ] [ col ] != word [ index ] ) return ; path += ( word [ index ] ) + " " + ( row ) . toString ( ) + " " + ( col ) . toString ( ) + " " ; if ( index == n ) { document . write ( path + " " ) ; return ; } for ( let k = 0 ; k < 8 ; ++ k ) if ( isvalid ( row + rowNum [ k ] , col + colNum [ k ] , prevRow , prevCol ) ) DFS ( mat , row + rowNum [ k ] , col + colNum [ k ] , row , col , word , path , index + 1 , n ) ; } function findWords ( mat , word , n ) { for ( let i = 0 ; i < ROW ; ++ i ) for ( let j = 0 ; j < COL ; ++ j ) if ( mat [ i ] [ j ] == word [ 0 ] ) DFS ( mat , i , j , - 1 , - 1 , word , " " , 0 , n ) ; } let mat = [ [ ' ' , ' ' , ' ' , ' ' , ' ' ] , [ ' ' , ' ' , ' ' , ' ' , ' ' ] , [ ' ' , ' ' , ' ' , ' ' , ' ' ] ] ; let word = " " . split ( " " ) ; findWords ( mat , word , word . length - 1 ) ;