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
.
题目链接:https://leetcode.com/problems/word-search/
题目分析:很基础的深度优先搜索,从第一个匹配的点开始搜
public class Solution {
public static int[] dx = {0, 1, 0, -1};
public static int[] dy = {1, 0, -1, 0};
public boolean DFS(int n, int m, int x, int y, int pos, int len, boolean[][] vis, char[][]board, String word) {
if (pos > len) {
return false;
}
if (pos == len) {
return true;
}
for (int i = 0; i < 4; i ++) {
int xx = x + dx[i];
int yy = y + dy[i];
if(xx >= 0 && yy >= 0 && xx < n && yy < m && !vis[xx][yy] && board[xx][yy] == word.charAt(pos)) {
vis[xx][yy] = true;
if(DFS(n, m, xx, yy, pos + 1, len, vis, board, word)) {
return true;
}
vis[xx][yy] = false;
}
}
return false;
}
public boolean exist(char[][] board, String word) {
int n = board.length;
int m = board[0].length;
int len = word.length();
if(len == 0) {
return false;
}
boolean[][] vis = new boolean[n][m];
for (int i = 0; i < n; i ++) {
Arrays.fill(vis[i], false);
}
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
if (board[i][j] == word.charAt(0)) {
vis[i][j] = true;
if (DFS(n, m, i, j, 1, len, vis, board, word)) {
return true;
}
vis[i][j] = false;
}
}
}
return false;
}
}