解题思路:
注意事项:
这个题目每个map[i][j]遍历顺序不同会影响结果,
不要使用vis[][]来记录是否走过!
参考代码:
import java.util.ArrayList;
import java.util.Scanner;
public class Main1 {
static int max = 0;
static int[] xx = {1, 0, -1, 0};
static int[] yy = {0, 1, 0, -1};
static int n;
static int m;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
char[][] map = new char[22][22];
String s = scanner.nextLine();
for (int i = 1; i <= n; i++) {
String str = scanner.nextLine();
for (int j = 1; j <=m; j++) {
map[i][j] = str.charAt(j-1);
}
}
// for(int i=0;i<=n+1;i++){
// for(int j=0;j<=m+1;j++){
// System.out.print(map[i][j]);
// }
// System.out.println();
// }
ArrayList<Character> table = new ArrayList<>();
table.add(map[1][1]);
dfs(table,map,1,1);
System.out.println(max);
}
public static void dfs(ArrayList<Character> list, char[][] map, int x, int y) {
max=Math.max(max,list.size());
for (int k = 0; k <= 3; k++) {
int dx = xx[k] + x;
int dy = yy[k] + y;
if ( dx>=1 && dx<=m && dy>=1 && dy<=n) {
boolean can = true;
for (int i = 0; i < list.size(); i++) {
if (map[dx][dy] == list.get(i)) {
can = false;
break;
}
}
if(can){
if(map[dx][dy]!='\0') {
list.add(map[dx][dy]);
dfs(list, map, dx, dy);
list.remove(list.size()-1);
}
}
}
}
}
}
0.0分
0 人评分