LETTERS(搜索与回溯)

版权声明:转载请注明出处链接 https://blog.csdn.net/qq_43408238/article/details/89390958

【题目描述】

给出一个roe×colroe×col的大写字母矩阵,一开始的位置为左上角,你可以向上下左右四个方向移动,并且不能移向曾经经过的字母。问最多可以经过几个字母。

【输入】

第一行,输入字母矩阵行数RR和列数SS,1≤R,S≤201≤R,S≤20。

接着输出RR行SS列字母矩阵。

【输出】

最多能走过的不同字母的个数。

【输入样例】

3 6
HFDFFB
AJHGDH
DGAGEH

【输出样例】

6

     一开始没看见开始的位置为左上角, 所以准备枚举每一个位置为起始位置,结果跑不出来。。。   

     常规DFS,dfs有三个参数,起始坐标和当前深度,设置一个全局量ans来记录最大递归深度。

#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<cmath>
#include <algorithm>
#include <stdlib.h>
#include <cstdio>
#include<sstream>
#include<cctype>
#include <set>
#include<queue>
#include <map>
#include <iomanip>
#define  INF  0x3f3f3f3f
typedef long long ll;
const ll MAX=1000000;
using namespace std;
ll  n,m;
char c[1000][1000];
bool judge[1000];
ll dir[][2]={{1,0},{0,1},{0,-1},{-1,0}};
ll ans=0;
void dfs(ll x,ll y,ll step)
{
    if(x<1||x>n||y<1||y>m) return ;

     ans=max(ans,step);
    for(ll i=0;i<=3;i++)
    {
        ll a=x+dir[i][0],b=y+dir[i][1];
        if(!judge[c[a][b]])
        {
            judge[c[a][b]]=1;
            dfs(a,b,step+1);
             judge[c[a][b]]=0;
        }

    }

}
int main()
{
    //freopen("input.txt","r",stdin);
    cin>>n>>m;
    for(ll i=1;i<=n;i++)
        for(ll j=1;j<=m;j++)
    {
        cin>>c[i][j];
    }
    judge[c[1][1]]=1;
    dfs(1,1,1);
    cout<<ans;



}

猜你喜欢

转载自blog.csdn.net/qq_43408238/article/details/89390958