Problem Description:
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells is those horizontally or V Ertically neighboring. The same letter cell is used more than once.
For example,
Given board =
[ [' A ', ' B ', ' C ', ' e '], [' s ', ' F ', ' C ', ' s '], [' A ', ' D ', ' e ', ' e ']]
Word = "ABCCED"
, returns true
,
Word = "SEE"
, returns true
,
Word = "ABCB"
, returns false
.
Algorithm analysis: Backtracking algorithm problem. Iterate through the alphabet matrix and then determine whether the upper and lower left and right sides of each letter match. Maintains an visited array to record the elements that have been accessed on the path, preventing repeated access.
public class wordsearch{private int row;private int col; public boolean exist (char[][] board, String word) {row = Board.length;col = board[0].length;boolean[][] visited = new bool ean[row][col];for (int i = 0; i < row; i++) {for (int j = 0; J < Col; J + +) {if (DFS (board, Word, 0, I, J, visited)) R Eturn true;}} return false;} Private Boolean DFS (char[][] board, String Word, int index, int rowindex,int colindex, boolean[][] visited) {if (index = = Word.length ())//word all matches, direct return Truereturn true;if (rowindex < 0 | | Colindex < 0 | | rowindex >= Row | | colindex > = col) return false;if (Visited[rowindex][colindex])//path previous access, ignoring return false;if (Board[rowindex][colindex]! = Word.charat (index))//mismatch, direct return falsereturn false;visited[rowindex][colindex] = true;//match, set visited to true// Whether the current element is matched or not, as long as there is a direction match, return Trueboolean res = DFS (board, Word, index + 1, rowindex-1, colindex,visited) | | DFS (board, Word, index + 1, rowindex + 1, colindex, visited) | | DFS (board, Word, index + 1, rowindex, COlindex + 1, visited) | | DFS (board, Word, index + 1, rowindex, colindex-1, visited); Visited[rowindex][colindex] = false;//resets visited to Falsere after recursion Turn res;}}
Word search, searching for strings in matrices, backtracking algorithms