Java实现 计蒜客 拯救行动
生活随笔
收集整理的這篇文章主要介紹了
Java实现 计蒜客 拯救行动
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
拯救行動
公主被惡人抓走,被關押在牢房的某個地方。牢房用 N \times M (N, M \le 200)N×M(N,M≤200) 的矩陣來表示。矩陣中的每項可以代表道路(@)、墻壁(#)、和守衛(x)。
英勇的騎士(r)決定孤身一人去拯救公主(a)。我們假設拯救成功的表示是 “騎士到達了公主所在的位置”。由于在通往公主所在位置的道路中可能遇到守衛,騎士一旦遇到守衛,必須殺死守衛才能繼續前進。
現假設騎士可以向上、下、左、右四個方向移動,每移動一個位置需要 11 個單位時間,殺死一個守衛需要花費額外的 11 個單位時間。同時假設騎士足夠強壯,有能力殺死所有的守衛。
給定牢房矩陣,公主、騎士和守衛在矩陣中的位置,請你計算拯救行動成功需要花費最短時間。
輸入格式
1、兩個整數代表 NN 和 M, (N, M \le 200)M,(N,M≤200).
2、隨后 NN 行,每行有 MM 個字符。"@" 代表道路,“a” 代表公主,“r” 代表騎士,“x” 代表守衛, “#” 代表墻壁。
輸出格式
如果拯救行動成功,輸出一個整數,表示行動的最短時間。
如果不可能成功,輸出 “Impossible”。
輸出時每行末尾的多余空格,不影響答案正確性
樣例輸入1
7 8 #@#####@ #@a#@@r@ #@@#x@@@ @@#@@#@# #@@@##@@ @#@@@@@@ @@@@@@@@樣例輸出1
13
樣例輸入2
樣例輸出2
7
PS:還差一個樣例,還望大佬指點
import java.util.LinkedList; import java.util.Scanner;public class Main {private static class Node {int x;int y;int step;public Node() {}public Node(int x, int y, int step) {this.x = x;this.y = y;this.step = step;}}private static int N = 220;private static LinkedList<Node> queue = new LinkedList<>();private static int r, c;private static char map[][] = new char[N][N];private static boolean vis[][] = new boolean[N][N];private static int dir[][] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};private static void bfs(int sx, int sy, int ex, int ey) {boolean flag = true;Node n = new Node(sx, sy, 0);queue.add(n);// vis[sx][sy] = true;while (!queue.isEmpty()) {Node nowP = queue.peek(); // int dis = nowP.step;if (nowP.x == ex && nowP.y == ey) {flag = false;if(nowP.step==0) flag=true;else System.out.println(nowP.step);break;} else {if (map[nowP.x][nowP.y] == 'x') {map[nowP.x][nowP.y] = '@';// vis[nowP.x][nowP.y] = false;queue.add(new Node(nowP.x, nowP.y, nowP.step + 1));} else {for (int i = 0; i < 4; i++) {int nx = nowP.x + dir[i][0];int ny = nowP.y + dir[i][1];if (nx >= 0 && nx < r && ny >= 0 && ny < c && !vis[nx][ny] && map[nx][ny] != '#') {vis[nx][ny] = true;queue.add(new Node(nx,ny,nowP.step+1));}}}}queue.pop();}if (flag) {System.out.println("Impossible");}}public static void main(String[] args) {int sx = 0, sy = 0, ex = 0, ey = 0;boolean bool1 = false ,bool2 = false; Scanner sc = new Scanner(System.in);r = sc.nextInt();c = sc.nextInt();//sc.nextLine();for (int i = 0; i < r; i++) {String s = sc.next();map[i] = s.toCharArray();}for (int i = 0; i < r; i++) {for (int j = 0; j < c; j++) {if (map[i][j] == 'r') {sx = i;sy = j;bool1=true;}if (map[i][j] == 'a') {ex = i;ey = j;bool2=true;// map[i][j] = '@';}}} if(bool1 && bool2)bfs(sx, sy, ex, ey);else System.out.println("Impossible");}}總結
以上是生活随笔為你收集整理的Java实现 计蒜客 拯救行动的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HTML制作简单课表
- 下一篇: Python基础1:数据类型、序列