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 =

[
  ["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;
}


 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值