洛谷P1825 Java解法

题目出处点这里
洛谷P1825 Java解法_第1张图片
思路:就是普通的广搜,不过要事先想办法把传送点相应的位置记录下来,值得注意的是此题中传送走过传送点时不用记录此点的访问状态,因为可以来回传送。

分析完之后代码就很简单了:

package search;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class P1852 {
	static int N, M, x0, y0, x1, y1;
	static int[] xx = { 0, 0, -1, 1 };
	static int[] yy = { -1, 1, 0, 0 };
	static String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	static int zzx0[] = new int[26], zzy0[] = new int[26], zzx1[] = new int[26], zzy1[] = new int[26];
	static int vis[][], count[] = new int[26];
	static char map[][];

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		M = sc.nextInt();
		map = new char[N][M];
		vis = new int[N][M];

		for (int i = 0; i < N; i++) {
			String str = sc.next();
			map[i] = str.toCharArray();
			if (str.contains("@")) {
				x0 = i;
				y0 = str.indexOf("@");
			}
			if (str.contains("=")) {
				x1 = i;
				y1 = str.indexOf("=");
			}
		}
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				if (s.contains(String.valueOf(map[i][j]))) {
					String str = String.valueOf(map[i][j]);
					int index = s.indexOf(str);
					count[index]++;
					if (count[index] == 1) {
						zzx0[index] = i;
						zzy0[index] = j;
					} else if (count[index] == 2) {
						zzx1[index] = i;
						zzy1[index] = j;
					}
					vis[i][j] = -1;// -1代表此地有传送装置

				}
			}
		}
		bfs();
	}

	public static void bfs() {
		Queue<node> q = new LinkedList<node>();
		q.add(new node(x0, y0, 0));
		vis[x0][y0] = 1;// 置为访问过
		while (!q.isEmpty()) {
			node n = q.poll();
			for (int i = 0; i < 4; i++) {
				int row = n.x + xx[i];
				int col = n.y + yy[i];
				if (row >= 0 && row < N && col >= 0 && col < M && vis[row][col] != 1 && map[row][col] != '#') {
					if (map[row][col] == '=') {//找到了出口就返回
						System.out.println(n.time + 1);
						return;
					}
					if (vis[row][col] == -1) {//代表踩到传送装置了
						String str = String.valueOf(map[row][col]);
						int index = s.indexOf(str);//找到索引
						//看看应该传送到哪个点
						if (zzx0[index] == row && zzy0[index] == col) {//那么就说明传送到另外一点
//							vis[zzx1[index]][zzy1[index]] = 1;
							q.add(new node(zzx1[index], zzy1[index], n.time+1));
						}else {
//							vis[zzx0[index]][zzy0[index]] = 1;
							q.add(new node(zzx0[index], zzy0[index], n.time+1));
						}
					}else {//如果踩到的不是传送装置
						q.add(new node(row, col, n.time+1));
					}
					vis[row][col] = 1;//记得此点也要置为访问过
				}
			}

		}
	}
}

class node {
	int x;
	int y;
	int time;

	public node(int x, int y, int time) {
		this.x = x;
		this.y = y;
		this.time = time;
	}

}

你可能感兴趣的:(洛谷)