您的位置:首页 > 其它

LeetCode 79 Word Search (DFS)

2016-08-31 10:35 459 查看
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
[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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: