Word Search
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.
DFS Backtracing
Time Complexity
O(mn)Space ComplexityO(n)思路
Find the first element of word in the board, if it matches, do dfs.
In dfs, there are two base cases, one is successful base, which is the index equals word length, then return true immediately, one is failed base case, which isif(i < 0 || i >= rows || j < 0 || j >= cols|| visited[i][j] == true || board[i][j] != word.charAt(index)) return false
Do dfs for four directions and we need to keep a visited, set visited[i][j] = true
, when it matches, but if the whole word doesn't match. It needs to do backtracing to set visited[i][j] = false
. 代码
public boolean exist(char[][] board, String word) { //corner case if(board == null || board.length == 0 || board[0] == null || board[0].length == 0 || word.length() == 0) return false; int rows = board.length, cols = board[0].length; boolean[][] visited = new boolean[rows][cols]; for(int i = 0; i < rows; i++){ for(int j = 0; j < cols; j++){ if(board[i][j] == word.charAt(0)){ if(dfs(board, word, i, j, 0, visited, rows, cols)) return true; } } } return false;}private boolean dfs(char[][] board, String word, int i, int j, int index, boolean[][] visited, int rows, int cols){ if(index == word.length()) return true; if(i < 0 || i >= rows || j < 0 || j >= cols|| visited[i][j] == true || board[i][j] != word.charAt(index)) return false; visited[i][j] = true; if(dfs(board, word, i - 1, j, index + 1, visited, rows, cols) || dfs(board, word, i + 1, j, index + 1, visited, rows, cols) || dfs(board, word, i, j + 1, index + 1, visited, rows, cols) || dfs(board, word, i, j - 1, index + 1, visited, rows, cols)) return true; visited[i][j] = false; return false;}
Follow up
When the efficiency of the method will be very low?
For example, word = "aaaaaab"The matrix is likea a a a aa a a a aa a a a bThe dfs will go really deep every time, but can't find the word.When the efficiency of the method will be very high?
For example, word = "xaaaab"The matrix is likea a x a aa a a a aa a a a bWe can just check the first letter and then decide if it need do dfs.