BFS_4:奇怪的电梯
有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步
输入格式
一行四个数据,棋盘的大小和马的坐标
输出格式
一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)
3 3 1 1
0 3 2
3 -1 1
2 1 4
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Node_4{
int x;
int step;
public Node_4(int x, int step) {
this.x = x;
this.step = step;
}
}
public class BFS_4 {
static int N = 210;
static int n;
static int[] mp = new int[N];
static int[] vis = new int[N] ;
static int start,end;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
start = scanner.nextInt();end = scanner.nextInt();
for (int i = 1; i <= n ; i++) {
mp[i] = scanner.nextInt();
}
Node_4 node = new Node_4(start,0);
dfs(node);
System.out.println(-1);
}
public static void dfs(Node_4 node) {
Queue<Node_4> queue = new LinkedList<>();
queue.offer(node);
vis[node.x] = 1;
while (!queue.isEmpty()){
Node_4 cur = queue.peek();
//出口条件
if(cur.x == end){
System.out.println(cur.step);
System.exit(0);
}
//进行不定方向的搜索
//电梯上方向
int dx = cur.x + mp[cur.x];
if(dx<=n&&vis[dx]==0){
//点与点之间的独立性
Node_4 temp = new Node_4(dx,cur.step+1);
queue.offer(temp);
vis[dx] = 1;
}
//电梯下方向
dx = cur.x - mp[cur.x];
if(dx>=1&&vis[dx]==0){
//点与点之间的独立性
Node_4 temp = new Node_4(dx,cur.step+1);
queue.offer(temp);
vis[dx] = 1;
}
queue.poll();
}
}
}