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"], ["ADEE"] ]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
解题思路:通过递归迭代的方法,每次都搜索一个字符,注意搜索条件是与上一个字符相邻位置。当最后全部字符都满足条件时候返回true;
#include<iostream>
#include<vector>
using namespace std;
const int Direction[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
bool SearchExit(vector<vector<char> > &board, vector<vector<bool> >&ExitFlag,int idx,int idy, string word)
{
if (word.size() == 0)//搜索完全部序列,返回true
return true;
for (int i = 0; i != 4;++i)//遍历4个方向
{
int point_x = idx + Direction[i][0];
int point_y = idy + Direction[i][1];
if (point_x >= 0 && point_x < board.size() && point_y >= 0&&point_y<board[point_x].size()&&word[0]==board[point_x][point_y]&&ExitFlag[point_x][point_y]==false)
{
ExitFlag[point_x][point_y] = true;
if (SearchExit(board, ExitFlag, point_x, point_y, word.substr(1)))
return true;
ExitFlag[point_x][point_y] = false;//若word.substr(1)字符串未能搜索到,将该点的FLAG置0;
}
}
return false;
}
bool exist(vector<vector<char> > &board, string word) {
if (board.empty())
return false;
vector<bool>Flagtmp(board[0].size(), false);
vector<vector<bool> >ExistFlagVevtor(board.size(), Flagtmp);
for (int i = 0; i != board.size();++i)
{
for (int j = 0; j != board[i].size();++j)
{
if (word[0]==board[i][j])
{
ExistFlagVevtor[i][j] = true;
if (SearchExit(board, ExistFlagVevtor, i, j, word.substr(1)))
return true;
ExistFlagVevtor[i][j] = false;
}
}
}
return false;
}