题目的大意是从第一行第一列的位置上开始移动问最远走多少步,直接采用DFS即可:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
using namespace std;
const int N = 30;
int row, col, maximum;
char matrix[N][N];
map<char, bool> m;
bool visited[N][N];
int pos[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
void dfs(int x, int y, int step){
bool flag = false; //用于判断是否还能够移动
for(int i = 0; i < 4; i ++ ){
int nx = x + pos[i][0];
int ny = y + pos[i][1];
if(nx < 0 || nx >= row || ny < 0 || ny >= col || visited[nx][ny] || m[matrix[nx][ny]]) continue;
flag = true;
visited[nx][ny] = true;
m[matrix[nx][ny]] = true;
dfs(nx, ny, step + 1);
visited[nx][ny] = false;
m[matrix[nx][ny]] = false;
}
if(!flag && maximum < step) maximum = step;
}
int main(){
while(scanf("%d%d", &row, &col) != EOF){
for(int i = 0; i < row; i ++ ) scanf("%s", matrix[i]);
memset(visited, false, sizeof(visited));
m.clear();
maximum = 0;
visited[0][0] = true;
m[matrix[0][0]] = true;
dfs(0, 0, 1);
printf("%d\n", maximum);
}
return 0;
}