Problem
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.
https://leetcode.com/problems/word-search/
Analysis
- 搜索,深度优先,注意终止条件;因为只是判断,不是例举所有的,可以提前终止。
- 因为字母只能使用一次,利用额外空间(m*n)记录,是否访问过;当然可以改变board本身,而不需要额外矩阵空间。但是这种可读性比较差,不推荐。
- 字符串的判断前缀,比较昂贵的操作,特别当字符串非常长;可以只比较第level层的字符是否相同。
Solution
public class WordSearch {
public boolean exist(char[][] board, String word) {
int r=board.length;
int c=board[0].length;
if(r*c < word.length()) return false;
char[] wdc = word.toCharArray();
boolean[][] visited = new boolean[r][c];
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if(dfs(board,visited,wdc,i,j,0)) return true;
}
}
return false;
}
boolean dfs(char[][] board, boolean[][] visited, char[] word, int x, int y, int level){
if(x<0||x>=board.length||y<0||y>=board[0].length) return false;
if(visited[x][y]) return false;
if(board[x][y]!=word[level]) return false;
if(level == word.length - 1) return true;
visited[x][y] = true;
if(dfs(board,visited,word,x+1,y, level + 1)) return true;
if(dfs(board,visited,word,x-1,y, level + 1)) return true;
if(dfs(board,visited,word,x,y+1, level+1)) return true;
if(dfs(board,visited,word,x,y-1,level + 1)) return true;
visited[x][y] = false;
return false;
}
}