# 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.
Subscribe to see which companies asked this question

public class Solution {
//this is a good problem
public boolean exist(char[][] board, String word) {
if(board == null || word == null || word.length() == 0)
return false;

for(int i =0; i < board.length; i ++) {
for(int j = 0; j < board[0].length; j++) {
if(dfs(board, i, j, word, 0, new boolean[board.length][board[0].length]))
return true;
}
}
return false;
}

private boolean dfs(char[][] board, int i, int j, String word, int index, boolean[][] isVisited) {
if(word.length() == index)
return true;
if(i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != word.charAt(index) || isVisited[i][j])
return false;

isVisited[i][j] = true;
if(dfs(board, i - 1, j, word, index + 1, isVisited))
return true;

if( dfs(board, i + 1, j, word, index + 1, isVisited))
return true;

if( dfs(board, i, j - 1, word, index + 1, isVisited))
return true;

if( dfs(board, i, j + 1, word, index + 1, isVisited))
return true;
//this statement is equal to the four statement above
// boolean res = dfs(board, i - 1, j, word, index + 1, isVisited) || dfs(board, i + 1, j, word, index + 1, isVisited) ||
//               dfs(board, i, j - 1, word, index + 1, isVisited) || dfs(board, i, j + 1, word, index + 1, isVisited);
isVisited[i][j] = false;
return false;
// return res;
}
}
• 本文已收录于以下专栏：

## word search

• 2015年03月24日 09:46
• 141KB
• 下载

## LeetCode OJ算法题（七十九）：Word Search

• op_yu
• 2014年08月27日 14:27
• 239

## Leetcode 79. Word Search (Medium) (cpp)

Leetcode 79. Word Search (Medium) (cpp)
• Niko_Ke
• 2016年07月31日 22:26
• 171

## hrbust 哈理工oj 1743 Word Search【DFS过】

hrbust 1743，哈理工oj 1743

## [LeetCode212] Word Search II

HARDGiven a 2D board and a list of words from the dictionary, find all words in the board.Each word ...

## [LeetCode] Word Search 的非递归实现

leetcode word search 的非递归实现
• hjh00
• 2015年11月01日 23:39
• 447

## LeetCode | Word Search

Given a 2D board and a word, find if the word exists in the grid. The word can be constructed fro...

## Word Search II 题解

• zslomo
• 2016年02月10日 15:34
• 340

举报原因： 您举报文章：Word Search 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)