4方向搜索递归

本文介绍了一种在二维字符矩阵中查找特定字符串的算法。通过深度优先搜索(DFS)策略,从矩阵的每个可能起点出发,按上下左右方向递归搜索目标字符串。实现了递归函数search,用于检查字符串是否存在于矩阵中,并最终返回查找结果。

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

#include <iostream>
#include <vector>
#include <map>
#include <string>

using namespace std;

int result = 0;
//输入要查找的单词以及单词大小:
string findmy = "mcn";
int sizeFind = 3;
vector<vector<char>>ininA = { { 'p','a','b','x' },{'a','m','c','h'},{'p','b','n','w'},{'q','g','h','t'} };

//查找单词findmy在不在这个矩阵里面,在不在的定义:从首字母开始,上下左右搜索得到即可。

vector<vector<int>>visited= { { -1,-1,-1,-1 },{ -1,-1,-1,-1 },{ -1,-1,-1,-1 },{ -1,-1,-1,-1 } };


//search():实现初始递归

void search(int idx,int row,int column)
{
    if (row < 0 || row>3 || column < 0 || column>3 || visited[row][column]==1)
        return;

    if (findmy[idx] != ininA[row][column])
        return;
    else
    {
        if (idx == sizeFind-1)
        {
            result = 1;
            return;
        }
        else
        {
            visited[row][column] = 1;
            search(idx + 1, row + 1, column);
            search(idx + 1, row - 1, column);
            search(idx + 1, row, column + 1);
            search(idx + 1, row, column - 1);
        }
    }

}

int main()
{
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
            cout << ininA[i][j]<<" ";
        cout  << endl;
    }
    cout <<"******"<< endl;
///////////////////////////////////////////////
    search(0, 1,1);
    if (result == 1) 
        cout << "yes" << endl;
    else
        cout << "no" << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值