# 题目

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 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)