LeetCode-Word Search

本文介绍了一种在二维网格中查找指定单词的算法实现。通过递归方式从每个格子出发,检查单词是否能由相邻格子的字符构成。文章包含完整的C++代码示例,演示了如何使用方向数组来遍历相邻单元格,并通过布尔矩阵记录已访问过的单元格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.


一道搜索题 ,只不过这道题要以每个点为起点开始搜,

AC:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

 

int nextt[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};//上右下左
int n,m;
vector<vector<bool>> visited;
//判断边界
bool inAway( int x , int y ){
	return ( x>=0 && x < m && y >= 0 && y < n );
}
bool searchWord( vector<vector<char>>& board, string word , int index , int startx , int starty ){

	if( index == word.size() - 1 )
		return word[index] == board[startx][starty];

        //因为单词是连续的  只有当前位置的字母和字母位置的索引相同  才能寻找下一个
	if( board[startx][starty] == word[index] ){

		visited[startx][starty] = true;
                
		for( int i = 0 ; i < 4 ; i ++ ){
			int newx = startx + nextt[i][0];
			int newy = starty + nextt[i][1];
			if( inAway( newx,newy ) && !visited[newx][newy] )
				if( searchWord( board , word , index+1 , newx , newy ) ) 
					return true;
		} 

		visited[startx][starty] = false;
	}
	return false;
}


bool exist(vector<vector<char>>& board, string word) {

	m = board.size();
	n = board[0].size();
	visited = vector<vector<bool> >(m,vector<bool>(n,false));
	for( int i = 0 ; i < board.size() ; i ++ )
		for( int j = 0 ; j < board[i].size() ; j ++ ){
			//从地图的每一个点当做起点开始搜  
			if( searchWord( board , word , 0 , i , j ) )
				return true;

		}

		return false;

}

int main()
{
	string s = "ABCB";
	vector<vector<char>> board;
	vector<char> v;
	
	v.push_back('A');
	v.push_back('B');
	v.push_back('C');
	v.push_back('E');
	board.push_back(v);
	v.clear();

	v.push_back('S');
	v.push_back('F');
	v.push_back('C');
	v.push_back('S');
	board.push_back(v);
	v.clear();

	v.push_back('A');
	v.push_back('D');
	v.push_back('E');
	v.push_back('E');
	board.push_back(v);
	v.clear();


	cout << exist(board,s) << endl; 
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值