【题目描述】
给出一个roe×col的大写字母矩阵,一开始的位置为左上角,你可以向上下左右四个方向移动,并且不能移向曾经经过的字母。问最多可以经过几个字母。
【输入】
第一行,输入字母矩阵行数R和列数S,1≤R,S≤20。
接着输出R行S列字母矩阵。
【输出】
最多能走过的不同字母的个数。
【输入样例】
3 6
HFDFFB
AJHGDH
DGAGEH
【输出样例】
6
思路分析:
迷宫问题
import java.util.*;
public class Main {
static char a[][]=new char[22][22];
static boolean c[][]=new boolean[22][22];
static int h[]=new int[]{-1,0,1,0};
static int l[]=new int[]{0,1,0,-1};
static int ans=0;
static int t[]=new int[200];//题目限制不能移向曾经已走过的字母
static int r;
static int s;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
r=sc.nextInt();
s=sc.nextInt();
for(int i=1;i<=r;i++){
String str=sc.next();
char b[]=str.toCharArray();
for(int j=1;j<=s;j++){
a[i][j]=b[j-1];
}
}
c[1][1]=true;
t[a[1][1]]=1;
dfs(1,1,1);
System.out.println(ans);
}
public static void dfs(int x,int y,int cnt) {
ans=Math.max(ans,cnt);
for(int i=1;i<=4;i++){//四中移动方案
int xx=x+h[i-1];
int yy=y+l[i-1];
if(xx>0&&xx<=r&&yy>0&&yy<=s&&!c[xx][yy]&&t[a[xx][yy]]==0){
c[xx][yy]=true;
t[a[xx][yy]]=1;
dfs(xx,yy,cnt+1);
c[xx][yy]=false;
t[a[xx][yy]]=0;
}
}
}
}