第一题涂色很简单,就是个简单的模拟
说说第二题吧,经典走迷宫问题,就是遇到*步数加一,遇到.直接前进,遇到#无法前进,只要走到四个边缘之一就算走出迷宫,问最小步数。
这题暴力dfs会超时,也就过个9%…
利用记忆化搜索加剪枝即可,贴个代码吧
import java.util.*;
public class Main {
static Scanner in = new Scanner(System.in);
static int n,m,ans ;
static char[][] mp;
static int[][] dp;
static int[][] bool;
static int[][] dir = {{0,1},{1,0},{0,-1},{-1,0}};
public static void dfs(int x, int y, int sp) {
if(x < 0 || x >= n || y < 0 || y >= m) {
ans = Math.min(sp, ans);
return;
}
if(bool[x][y]==1) return;
if(sp >= dp[x][y]) {//key code 步数更大的直接返回
return;
} else {
dp[x][y] = sp;//步数更小的则直接更新
}
bool[x][y] = 1;
if(mp[x][y] == '#') return;
if(mp[x][y] == '*') sp++;
int tx,ty;
for(int i = 0; i < 4; i++) {
tx = x+dir[i][0];
ty = y+dir[i][1];
dfs(tx,ty, sp);
}
bool[x][y] = 0;
}
public static void main(String[] args) {
int t = in.nextInt();
while(t-->0){
ans = Integer.MAX_VALUE;
n = in.nextInt();
m = in.nextInt();
mp = new char[n][m];
dp = new int[n][m];
bool = new int[n][m];
int x = 0,y =0 ;
for (int i = 0; i < n; i++) {
mp[i] = in.next().toCharArray();
for (int j = 0; j < m; j++) {
if(mp[i][j] == '@'){
x = i;
y = j;
}
dp[i][j] = Integer.MAX_VALUE;
bool[i][j] = 0;
}
}
dfs(x,y,0);
if(ans == Integer.MAX_VALUE)
System.out.println(-1);
else
System.out.println(ans);
}
}
}
简单测试用例:
3
3 4
####
#@.*
**.*
0
3
3
###
#@#
.#.
-1
3 3
###
#@*
.**
1