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 are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"]]
WORD ="ABCCED"
,-> Returnstrue
,
WORD ="SEE"
,-> Returnstrue
,
WORD ="ABCB"
,-> Returnsfalse
.
What we use to save data is a two-dimensional array and a question about how to find feasible solutions. Naturally, we will think deeply. Because the most common problem in deep search is to find the total number of feasible solutions, find a feasible solution, and find all feasible solutions. All we need to do is to express the state and store the necessary data for a State so that we can provide complete information on how to extend to the next state. Deep Search generally uses the method of adding function parameters. The next step is to judge the weight. In this question, we use a two-dimensional array to store data. We can open a large Boolean array to indicate the access to each data during each recursion. Finally, we need to know the conditions for termination and convergence. In many cases, the conditions for convergence and termination are combined. We use the pruning method to accelerate this question, because another acceleration method, cache is generally used when the status transition graph is a dag, and there are overlapping subproblems, hashmap can be used.
Java:
public class Solution { public boolean exist(char[][] board, String word) { int rank = board.length; int row = board[0].length; boolean visited[][] = new boolean[rank][row]; for (int i = 0; i < rank; i++) { for (int j = 0; j < row; j++) { if (dfs(board,word,0,i,j,visited)) { return true; } } } return false; } public boolean dfs(char board[][], String word, int index, int x, int y, boolean visited[][]) { if (index == word.length()) { return true; } if (x < 0 || y < 0 || y >= board[0].length || x >= board.length) { return false; } if (visited[x][y]) { return false; } if (board[x][y] != word.charAt(index) ) { return false; } visited[x][y] = true; boolean result = dfs(board, word, index+1, x+1, y, visited) || dfs(board, word, index+1, x, y+1, visited) || dfs(board, word, index+1, x-1, y, visited) || dfs(board, word, index+1, x, y-1, visited); visited[x][y] = false; return result; }}
Word search | leetcode