【题目描述】
给出一个roe×col的大写字母矩阵,一开始的位置为左上角,你可以向上下左右四个方向移动,并且不能移向曾经经过的字母。问最多可以经过几个字母。
【输入】
第一行,输入字母矩阵行数RR和列数SS,1≤R,S≤20。
接着输出R行S列字母矩阵。
【输出】
最多能走过的不同字母的个数。
【输入样例】
3 6
HFDFFB
AJHGDH
DGAGEH
【输出样例】
6
【思路】
这道题的思路还是比较简单的哈,就是普通的深搜,代码如下,看不懂的我在旁边有注释,可以看看,懂得当我没说!
【代码】
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#define N 30
using namespace std;
int r, s;
char a[N][N];
int vis[N][N];
int num[26];
int dir[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
int maxx = 0;//最大路过数量
void dfs(int x, int y, int step)//x,y为起始点的横纵坐标,step表示的路过的数量
{
if (maxx < step)
maxx = step;//若step更大,则maxx更新
for (int i = 0; i < 4; i++)
{
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if (nx >= 0 && nx < r && ny >= 0 && ny < s && vis[nx][ny] == 0 && num[a[nx][ny] - 'A'] == 0)//如果搜索的格子在界限内,且没被搜索过,且不是重复字母,运行下面程序
{
vis[nx][ny] = 1;//标记为搜索成功
num[a[nx][ny] - 'A'] = 1;//字母更改
dfs(nx, ny, step + 1);//继续搜索
vis[nx][ny] = 0;//因为下次继续要用,所以数据还原
num[a[nx][ny] - 'A'] = 0;
}
}
}
int main()
{
cin >> r >> s;
for (int i = 0; i < r; i++)
for (int j = 0; j < s; j++)
cin >> a[i][j];//输入字母
num[a[0][0] - 'A'] = 1;//若NUM[字母的ASCII码]=1,说明这个字母已被访问
vis[0][0] = 1;//已经搜索过(0,0)区域
dfs(0, 0, 1);//进行搜索
cout << maxx << endl;
return 0;
}
当然如果不要注释,也可以,净化版代码如下:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
char a[30][30];
int num[30];
int vis[30][30];
int maxx = 0;
int r, s;
int dir[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
void dfs(int x, int y, int step)
{
if (maxx < step)
{
maxx = step;
}
for (int i = 0; i < 4; i++)
{
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if (nx >= 0 && nx < r && ny >= 0 && ny < s && vis[nx][ny] == 0 && num[a[nx][ny] - 'A'] == 0)
{
vis[nx][ny] = 1;
num[a[nx][ny] - 'A'] = 1;
dfs(nx, ny, step + 1);
vis[nx][ny] = 0;
num[a[nx][ny] - 'A'] = 0;
}
}
}
int main()
{
cin >> r >> s;
for (int i = 0; i < r; i++)
for (int j = 0; j < s; j++)
cin >> a[i][j];
num[a[0][0] - 'A'] = 1;
vis[0][0] = 1;
dfs(0, 0, 1);
cout << maxx << endl;
return 0;
}