# LeetCode 79 Word Search (DFS)

286人阅读 评论(0)

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.

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;
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：567558次
• 积分：13424
• 等级：
• 排名：第955名
• 原创：800篇
• 转载：7篇
• 译文：0篇
• 评论：119条
博客专栏
 LeetCode 文章：126篇 阅读：52928
 Java学习笔记 文章：10篇 阅读：5656
 算法题 文章：47篇 阅读：23729
阅读排行