第一题、模拟涂色游戏
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inHand = sc.nextLine();
String toPrint = sc.nextLine();
if(inHand==null || inHand.length()==0 || toPrint==null || toPrint.length()==0) System.out.println(0);
char[] colors = inHand.toCharArray();
char[] boards = toPrint.toCharArray();
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < colors.length; i++) {
if(Character.isUpperCase(colors[i])){
map.put(colors[i],map.getOrDefault(colors[i],0)+1);
}
}
int count = 0;
for (int i = 0; i < boards.length; i++) {
if(Character.isUpperCase(boards[i])){
if(map.containsKey(boards[i]) && map.get(boards[i])>=1){
map.put(boards[i],map.get(boards[i])-1);
count++;
}
}
}
System.out.println(count);
}
}
第二题 迷宫dfs
// 输入描述
// 多组数据,第1行有1个正整数T,表示有T组数据。(T<=100)
//
// 对于每组数据,第1行有两个整数N和M。(1<=N, M<=1000)
//
// 接着N行,每行有一个长度为M的字符串,表示N*M的迷宫。
//
// 输出描述
// 输出一个整数,表示使用特异功能的最少次数。如果小昆虫不能走出迷宫,则输出-1。
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static boolean flag;
static int ans;
static int[][] dir = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
static boolean[][] vis;
static int[][] cost;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
int n, m, sx, sy;
char[][] map;
while (T-- > 0) {
n = in.nextInt();
m = in.nextInt();
in.nextLine();
map = new char[n][m];
vis = new boolean[n][m];
cost = new int[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.next().toCharArray();
Arrays.fill(cost[i], 0x3f3f3f3f);
}
sx = 0;
sy = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j] == '@') {
sx = i;
sy = j;
}
}
}
flag = false;
vis[sx][sy] = true;
dfs(sx, sy, map, n, m);
if (flag) {
System.out.println(0);
continue;
}
flag = false;
ans = Integer.MAX_VALUE;
cost[sx][sy] = 0;
dfs(sx, sy, map, n, m, cost[sx][sy]);
System.out.println(flag ? ans : -1);
}
}
static void dfs(int x, int y, char[][] map, int n, int m) {
if (flag)
return;
for (int i = 0; i < 4; i++) {
int dx = x + dir[i][0], dy = y + dir[i][1];
// 出界了
if (!check(dx, dy, n, m)) {
flag = true;
} else if (!vis[dx][dy] && map[dx][dy] == '.') {
vis[dx][dy] = true;
dfs(dx, dy, map, n, m);
}
}
}
static void dfs(int x, int y, char[][] map, int n, int m, int cnt) {
for (int i = 0; i < 4; i++) {
int dx = x + dir[i][0], dy = y + dir[i][1];
// 出界了
if (!check(dx, dy, n, m)) {
flag = true;
ans = Math.min(ans, cnt);
} else if (map[dx][dy] != '#') {
if (map[dx][dy] == '*' && cost[x][y] + 1 < cost[dx][dy]) {
cost[dx][dy] = cost[x][y] + 1;
dfs(dx, dy, map, n, m, cost[dx][dy]);
} else if (map[dx][dy] == '.' && cost[x][y] < cost[dx][dy]) {
cost[dx][dy] = cost[x][y];
dfs(dx, dy, map, n, m, cost[dx][dy]);
}
}
}
}
static boolean check(int x, int y, int n, int m) {
return x >= 0 && y >= 0 && x < n && y < m;
}
}