信息学奥赛一本通 1212:LETTERS | OpenJudge NOI 2.5 156:LETTERS

【题目链接】

ybt 1212:LETTERS
OpenJudge NOI 2.5 156:LETTERS

【题目考点】

1. 深搜

【解题思路】

设bool类型vis数组,长度为128。vis[i]为真表示ascii码为i的字母已经访问过。
设变量step记录已经访问过的字母数量,mx记录访问过的字母数量的最大值。
每遍历到一个位置,搜索其上下左右四个位置,如果这个位置在地图内,且这个位置的字符没有被访问过,则更改字母的访问状态,包括vis数组及step变量(在此处更新step最大值mx),接着搜索这一新的位置。在搜索后,记得状态还原。
深搜的具体写法上,有在函数调用前访问,以及在函数调用内访问两种写法,区别仅仅在于作为参数传入的位置在函数内部是否处于已访问的状态。

【题解代码】

写法1:在函数调用前访问
#include <bits/stdc++.h>
using namespace std;
#define N 25
int r, s, step, mx;
char mp[N][N];
bool vis[128];
int dir[4][2] = {{0,1},{0,-1},{-1,0},{1,0}};
void dfs(int sx, int sy)//在函数调用前访问 
{
    for(int i = 0; i < 4; ++i)
    {
        int x = sx + dir[i][0], y = sy + dir[i][1];
        if(x >= 1 && x <= r && y >= 1 && y <= s && vis[mp[x][y]] == false)
        {
            vis[mp[x][y]] = true;//更新状态 
            step++;
            mx = max(step, mx);
            dfs(x, y);
            step--;//状态还原 
            vis[mp[x][y]] = false;
        }
    }
}

int main()
{
    cin >> r >> s;
    for(int i = 1; i <= r; ++i)
        for(int j = 1; j <= s; ++j)
            cin >> mp[i][j];
    vis[mp[1][1]] = true;//访问初始位置 
    step = 1;
    mx = 1;
    dfs(1,1);
    cout << mx;
    return 0;
}
写法2:在函数调用内访问
#include <bits/stdc++.h>
using namespace std;
#define N 25
int r, s, step, mx;
char mp[N][N];//地图 
bool vis[128];//vis[i]:ascii码为i的字母是否已经被访问过 
int dir[4][2] = {{0,1},{0,-1},{-1,0},{1,0}};//方向数组 
void dfs(int sx, int sy)//在函数调用内访问 
{
	if(sx >= 1 && sx <= r && sy >= 1 && sy <= s && vis[mp[sx][sy]] == false)//如果(sx,sy)在地图内且该位置的字母没有访问过 
    {
    	vis[mp[sx][sy]] = true;//访问该字母 
        step++;//移动步数加1 
        mx = max(step, mx);//更新最大值 
	    for(int i = 0; i < 4; ++i)//搜索上下左右四个位置 
	    {
	        int x = sx + dir[i][0], y = sy + dir[i][1];
	        dfs(x, y);
	    }
	    step--;//状态还原 
	    vis[mp[sx][sy]] = false;
	}
}
int main()
{
    cin >> r >> s;
    for(int i = 1; i <= r; ++i)
        for(int j = 1; j <= s; ++j)
            cin >> mp[i][j];
    dfs(1,1);
    cout << mx;
    return 0;
}
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值