一、题目描述
给出一个row×col的大写字母矩阵,一开始的位置为左上角,你可以向上下左右四个方向移动,并且不能移向曾经经过的字母。问最多可以经过几个字母。
输入
第一行,输入字母矩阵行数R和列数S,1≤R,S≤20。
接着输出R行S列字母矩阵。
输出
最多能走过的不同字母的个数。
3 6
HFDFFB
AJHGDH
DGAGEH
输出样例
6
二、题解
方法一:dfs
错误思路: 直接用一个 set 存储每一步经过的字符,如果遍历到重复字符,我们跳过,最后返回 set 的大小。
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
static int R, C;
static char[][] g;
final static int[][] dir = { {1, 0}, {0, -1}, {-1, 0}, {0, 1}};
static boolean[][] vis;
static Set<Character> set;
private static void dfs(int x, int y) {
for (int k = 0; k < 4; k++) {
int tx = x + dir[k][0];
int ty = y + dir[k][1];
if (tx < 0 || tx >= R || ty < 0 || ty >= C || vis[tx][ty] || set.contains(g[tx][ty]))
continue;
vis[tx][ty] = true;
set.add(g[tx][ty]);
dfs(tx, ty);
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
R = sc.nextInt();
C = sc.nextInt();
g = new char[R][C];
for(int i = 0; i < R; i++) {
String s = sc.next();
for(int j = 0; j < C; j++) {
g[i][j] = s.charAt(j);
}
}
vis = new boolean[R][C];
set = new HashSet<>();
vis[0][0] = true;
set.add(g[0][0]);
dfs(0, 0);
System.out.println(set.size());
}
}
查缺补漏:有可能遍历的时候,set 中存在着很多字符,比最后 set 的大小还要大,但是你没去实时记录。所以我把代码改成这样:
private static void dfs(int x, int y) {
max = Math.max(set.size(), max);
for (int k = 0; k < 4; k++) {
int tx = x + dir[k][0];
int ty = y + dir[k][1];
if (tx < 0 || tx >= R || ty < 0 || ty >= C || vis[tx][ty] || set.contains(g[tx][ty]))
continue;
vis[tx][ty] = true; //注
set.add(g[tx][ty]);
dfs(tx, ty);
set.remove(g[tx][ty]);
}
}
还是 WA(5分):为什么呢?这是一道回溯题啊…,已经很明显了,题目从起点出发,问最多经过的不同字符,也就是说,我们要从每一个位置都跑完整个网格,而不是只从起点跑一编,这样的复杂度是 ,回溯是
代码更正如下:
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
static int R, C;
static char[][] g;
final static int[][] dir = { {1, 0}, {0, -1}, {-1, 0}, {0, 1}};
static boolean[][] vis;
static Set<Character> set;
static int max;
private static void dfs(int x, int y) {
max = Math.max(set.size(), max);
for (int k = 0; k < 4; k++) {
int tx = x + dir[k][0];
int ty = y + dir[k][1];
if (tx < 0 || tx >= R || ty < 0 || ty >= C|| set.contains(g[tx][ty]))
continue;
set.add(g[tx][ty]);
dfs(tx, ty);
set.remove(g[tx][ty]);
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
R = sc.nextInt();C = sc.nextInt();
g = new char[R][C];
for(int i = 0; i < R; i++) {
String s = sc.next();
for(int j = 0; j < C; j++) {
g[i][j] = s.charAt(j);
}
}
set = new HashSet<>();
set.add(g[0][0]);
dfs(0, 0);
System.out.println(max);
}
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,