AcWing 1111. 字母 解题思路及代码

先贴个题目:

简单的dfs,没啥难点,直接上代码。

cpp 复制代码
#include<iostream>
#include<cmath>
using namespace std;

const int N = 30;

int r, s;
int ans = 0;
char map[N][N];
bool st[26];
int dx[4] = {0, 0, -1, 1}, dy[4] = {1, -1, 0, 0};

void dfs(int x,int y,int cnt)
{
    bool sign = false;
    st[map[x][y] - 'A'] = true;
    for (int i = 0; i < 4;++i)
    {
        int tx = x + dx[i];
        int ty = y + dy[i];
        if(tx<0||tx>=r||ty<0||ty>=s)
        {
            continue;
        }
        if(!st[map[tx][ty]-'A'])
        {
            sign = true;
            dfs(tx, ty, cnt + 1);
        }
    }
    st[map[x][y] - 'A'] = false;
    if(!sign)
    {
        ans = max(ans, cnt);
        return;
    }
}

int main()
{
    cin >> r >> s;
    for (int i = 0; i < r;++i)
        scanf("%s", map[i]);
    st[map[0][0]-'A']=true;
    dfs(0, 0, 1);
    cout << ans;
}

by------------2024.4.11刷题记录

相关推荐
mjhcsp几秒前
C++ 梯度下降法(Gradient Descent):数值优化的核心迭代算法
开发语言·c++·算法
yunyun321237 分钟前
跨语言调用C++接口
开发语言·c++·算法
m0_5180194810 分钟前
C++中的装饰器模式变体
开发语言·c++·算法
xushichao198917 分钟前
高性能密码学库
开发语言·c++·算法
m0_5180194820 分钟前
C++代码混淆与保护
开发语言·c++·算法
m0_5698814722 分钟前
C++中的智能指针详解
开发语言·c++·算法
blackicexs25 分钟前
第九周第三天
算法
自信1504130575935 分钟前
选择排序算法
c语言·数据结构·算法·排序算法
2401_8735449236 分钟前
基于C++的游戏引擎开发
开发语言·c++·算法
add45a37 分钟前
C++中的组合模式
开发语言·c++·算法