# 题目

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 =

[
[“ABCE”],
[“SFCS”],
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false

# 代码

class Solution {
public:
bool search(vector<vector<char>>& board, vector<vector<bool>> &flag, int x, int y, string &word, int start){
int m = board.size();
int n = board[0].size();
if(start == word.length())
return true;
if(x < 0 || x >= m || y < 0 || y >= n || flag[x][y] || word.at(start) != board[x][y])
return false;
flag[x][y] = true;
bool ans = search(board, flag, x+1, y, word, start+1) ||
search(board, flag, x-1, y, word, start+1) ||
search(board, flag, x, y+1, word, start+1) ||
search(board, flag, x, y-1, word, start+1);
flag[x][y] = false;
return ans;
}
bool exist(vector<vector<char>>& board, string word) {
int m = board.size();
if(m == 0)
return false;
int n = board[0].size();
vector<vector<bool> > flag(m, vector<bool> (n, false));
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(search(board, flag, i, j, word, 0))
return true;
}
}
return false;
}
};

#### Leetcode Word Search 解题报告

2014-01-09 15:34:26

#### Word Search -- LeetCode

2014-04-23 01:21:12

#### leetcode 212: Word Search II

2015-05-20 06:34:38

#### 【LeetCode】Word Search II 解题报告

2015-05-19 16:52:33

#### LeetCode79——Word Search

2015-11-17 21:53:26

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

2016-03-20 15:07:55

#### [python]leetcode(79). Word Search

2017-09-19 22:00:21

#### LeetCode79:Word Search

2015-07-02 15:42:11

#### leetcode 211: Add and Search Word - Data structure design

2015-05-19 06:12:01

#### [Leetcode] 212. Word Search @python

2016-02-25 19:59:33

## 不良信息举报

leetcode Word Search