【题目】
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
.
【题意】
给你一个二维字母的数组,可以上下左右走,查找是否某个单词是否存在。同一位置的字母不可以被使用多次。
【分析】
基本思路是使用DFS来对一个起点字母上下左右搜索,看是不是含有给定的Word。还要维护一个visited数组,表示从当前这个元素是否已经被访问过了,过了这一轮visited要回false,因为对于下一个元素,当前这个元素也应该是可以被访问的。
【实现】
public class Solution {
public boolean exist(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
boolean[][] visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (dfs(board, visited, i, j, word, 0)) return true;
}
}
return false;
}
public boolean dfs(char[][] board, boolean[][] visited, int x, int y, String word, int k) {
if (k == word.length()) return true;
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.charAt(k)) return false;
visited[x][y] = true;
if (dfs(board, visited, x - 1, y, word, k + 1)) return true;
if (dfs(board, visited, x + 1, y, word, k + 1)) return true;
if (dfs(board, visited, x, y - 1, word, k + 1)) return true;
if (dfs(board, visited, x, y + 1, word, k + 1)) return true;
visited[x][y] = false;
return false;
}
}