79. 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.
For example,
Given board=
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
https://leetcode.com/problems/word-search/\#/description
Analysis:
DFS, have a visited array to keep track of each dfs dive what has been visited so we dont go into circles.
Complexity:
Time: O(4^n)
Space: O(n)
Code:
public class Solution {
private int[] dirx = new int[]{-1, 1, 0, 0};
private int[] diry = new int[]{0, 0, -1, 1};
private int ROW = 0, COL = 0;
public boolean exist(char[][] board, String word) {
if(board == null || board.length == 0 || board[0].length == 0 || word == null || word.length() == 0){
return false;
}
ROW = board.length;
COL = board[0].length;
char[] wd = word.toCharArray();
//find the letter first
for(int i = 0; i < ROW; i++){
for(int j = 0; j < COL; j++){
if(board[i][j] == wd[0]){
int[][] visited = new int[ROW][COL];
visited[i][j] = 1;
if(dfs(wd, board, visited, i, j, 1)){
return true;
}
}
}
}
return false;
}
private boolean dfs(char[] wd, char[][] board, int[][] visited, int x, int y, int pos){
if(pos == wd.length){
return true;
}
for(int i = 0; i < 4; i ++){
int xx = x + dirx[i];
int yy = y + diry[i];
if(xx < 0 || xx >= ROW || yy < 0 || yy >= COL || board[xx][yy] != wd[pos] || visited[xx][yy] == 1) continue;
visited[xx][yy] = 1;
if(dfs(wd, board, visited, xx, yy, pos+1)){
return true;
}
visited[xx][yy] = 0;
}
return false;
}
}