先贴个题目:
简单的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刷题记录