Middle-题目108：79. Word Search

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 boolean exist(char[][] board, String word) {
int row = board.length;
if(row==0)
return false;
int col = board[0].length;
boolean[][] visited = new boolean[row][col];
for(int i = 0;i<row;i++) {
for(int j=0;j<col;j++) {
if(word.charAt(0) == board[i][j]) {
if(dfs(board, i, j, visited, word, 0))
return true;
}
}
}
return false;
}

private boolean dfs(char[][] board, int i, int j, boolean[][] visited, String word, int index) {
if(index == word.length())
return true;
else if(i<0 || i>board.length-1 || j<0 || j>board[0].length-1 || word.charAt(index)!=board[i][j] || visited[i][j])
return false;
else {
visited[i][j]=true;
boolean result = dfs(board, i-1, j, visited, word, index+1) || dfs(board, i+1, j, visited, word, index+1) || dfs(board, i, j-1, visited, word, index+1) || dfs(board, i, j+1, visited, word, index+1);
visited[i][j] = false;
return result;
}

}
}

13ms,beats 58.16%,众数14ms,14.58%
cmershen的碎碎念：

LeetCode79——Word Search

2015-11-17 21:53:26

[python]leetcode(79). Word Search

2017-09-19 22:00:21

LeetCode 79（Word Search）java

2017-01-04 22:54:22

LeetCode79:Word Search

2015-07-02 15:42:11

LeetCode-79-Word Search(回溯法)-Medium

2016-03-20 15:07:55

LeetCode 79 Word Search (Python详解及实现)

2017-08-08 15:30:56

[C++]LeetCode: 97 Word Search (深度优先搜索)

2015-01-15 14:05:38

Leetcode_c++： Word Search (079）

2016-06-06 23:39:24

leetcode 79. Word Search | Java最短代码实现

2016-03-09 12:45:06

79. Word Search(Python3)

2018-01-29 15:24:03