LeetCode 79 Word Search (DFS)

404人阅读 评论(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;
}
}

个人资料
等级：
访问量： 76万+
积分： 1万+
排名： 867
博客专栏
 算法题 文章：51篇 阅读：35233 Java学习笔记 文章：10篇 阅读：12013 LeetCode 文章：138篇 阅读：80130