测试样例
Input:
9 5
+++++++++
+++++++++
+++++++++
+++++++++
+++++++++
***+*****
+++++++++
+++++++++
+++++++++
Output:
16
题目解析:这道题的解法是BFS,比较关键的点就是根据time<=k(一定要注意这里是小于等于!)、time>k&&time<=k*2、time>=k*2分成三种情况来讨论,然后就是BFS的标准流程
import java.util.LinkedList;
import java.util.Scanner;
public class 大胖子走迷宫 {
static int [][]move={{-1,0},{1,0},{0,-1},{0,1}};
static int [][]record;
static char [][]map;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n=scanner.nextInt();
int k=scanner.nextInt();
map=new char[n+1][n+1];
scanner.nextLine();
for (int i = 1; i <= n; i++) {
String s1=scanner.nextLine();
for (int j = 1; j < map.length; j++) {
map[i][j]=s1.charAt(j-1);
}
}
record = new int[n+1][n+1];
LinkedList<ros> queue = new LinkedList<>();
queue.add(new ros(3,3,0));
record[3][3]=1;
while(true)
{
ros now=queue.poll();
int x=now.x;
int y=now.y;
int time= now.time;
if(x==n-2&&y==n-2)
{
System.out.println(time);
break;
}
if(time<=k)
{
for (int i = 0; i < move.length; i++) {
boolean key=true;
int x1=x+move[i][0];
int y1=y+move[i][1];
if(x1<3||x1>n-2||y1<3||y1>n-2||record[x1][y1]==1||map[x1][y1]=='*') continue;
if(move[i][0]!=0) {
for (int j = y - 2; j <= y + 2; j++) {
if (map[x1][j] == '*') {
key = false;
break;
}
}
}
if(move[i][1]!=0) {
for (int j = x - 2; j <= x + 2; j++) {
if (map[j][y1] == '*') {
key = false;
break;
}
}
}
if(key)
{
record[x1][y1]=1;
// System.out.println(x1+" "+y1+" "+(time+1));
queue.add(new ros(x1,y1,time+1));
}
else
{
// record[x][y]=0;
queue.add(new ros(x,y,time+1));
}
}
}
else if(time>k&&time<=k*2)
{
for (int i = 0; i < move.length; i++) {
boolean key=true;
int x1=x+move[i][0];
int y1=y+move[i][1];
if(x1<2||x1>n-1||y1<2||y1>n-1||record[x1][y1]==1) continue;
if(move[i][0]!=0)
for (int j = y-1; j <=y+1 ; j++) {
if(j<1||j>n||map[x1][j]=='*')
{
key=false;
break;
}
}
if(move[i][1]!=0)
for (int j = x-1; j <=x+1 ; j++) {
if(j<1||j>n||map[j][y1]=='*')
{
key=false;
break;
}
}
if(key)
{
record[x1][y1]=1;
// System.out.println(x1+" "+y1+" "+(time+1));
queue.add(new ros(x1,y1,time+1));
}
else
{
//record[x][y]=0;
queue.add(new ros(x,y,time+1));
}
}
}
else
{
for (int i = 0; i < move.length; i++) {
int x1=x+move[i][0];
int y1=y+move[i][1];
if(x1>=1&&x1<=n&&y1>=1&&y1<=n&&record[x1][y1]==0&&map[x1][y1]=='+')
{
record[x1][y1]=1;
// System.out.println(x1+" "+y1+" "+(time+1));
queue.add(new ros(x1,y1,time+1));
}
}
}
}
}
}
class ros
{
int x;
int y;
public ros(int x, int y, int time) {
this.x = x;
this.y = y;
this.time = time;
}
int time;
}