【题目链接】
ybt 1212:LETTERS
OpenJudge 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;
}