2.22 Word Search
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 are those horizontally or vertically neighboring. The same letter cell may not be 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.
Method
we need to search each characters in the string to make sure that this word is in the matrix. For each elements in the matrix, it can be a begining of the string. if it is , it has four directions to continue, except those element in sides.
so it is a dfs problem, when we find start pointer in the matrix, we can do the next level to search the remain of the string in four directions.
Time and Space Complexity
Code
public class Solution {
public boolean exist(char[][] board, String word) {
if (word == null || word.length() == 0 || board == null || board.length == 0){
return false;
}
int m = board.length;
int n = board[0].length;
boolean[][] visited = new boolean[m][n];
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board[i].length; j++){
if (board[i][j] == word.charAt(0)){
if (helper(board, word, 0, i, j,visited)){
return true;
}
}
}
}
return false;
}
public boolean helper(char[][] board, String word, int index, int i, int j,boolean[][] visited){
if (index == word.length()){
return true;
}
if (i < 0 || i >= board.length || j < 0 || j >= board[i].length){
return false;
}
if (board[i][j] != word.charAt(index) || visited[i][j]){
return false;
}
visited[i][j] = true;
boolean res = helper(board, word, index + 1, i + 1, j, visited) ||
helper(board, word, index + 1, i, j + 1, visited) ||
helper(board, word, index + 1, i, j - 1, visited) ||
helper(board, word, index + 1, i - 1, j, visited);
visited[i][j] = false;
return res;
}
}