洛谷P1746 Java解法

题目出处
在这里插入图片描述
思路:很明显又是广搜,加一个为1的地方不能走的判断即可。不过还是要注意每找到一个可以走的地方就要标记为走过,如果不标记就会浪费大量时间重复走过的坐标,甚至可能TLE。

代码如下:

package search;

import java.awt.Point;
import java.util.List;
import java.util.Scanner;
import java.util.Vector;

public class P1746 {

	static int n, x1, y1, x2, y2;
	static char[][] map;
	static int[] xx = { 1, -1,0, 0 };
	static int[] yy = { 0, 0, 1, -1 };
	static List<Point> p = new Vector<Point>(1000001);
	static List<Integer> step = new Vector<Integer>(1000001);// 存储走到这里用了几步

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		map = new char[n+1][n+1];
		for (int i = 1; i <= n; i++) {
			char[] temp = sc.next().toCharArray();
			for (int j = 1; j <= n; j++) {
				map[i][j] = temp[j-1];
			}
		}
		x1 = sc.nextInt();
		y1 = sc.nextInt();
		x2 = sc.nextInt();
		y2 = sc.nextInt();
		bfs();
	}

	public static void bfs() {
		boolean[][] vis = new boolean[1001][1001];
		p.add(new Point(x1, y1));
		step.add(0);
		vis[x1][y1] = true;//事先把x1,y1标记为走过,防止以后又走到这一步
		while (!p.isEmpty()) {
			Point pp = p.remove(0);
			int x = pp.x;
			int y = pp.y;
			int s = step.remove(0);
			for (int i = 0; i < 4; i++) {
				if (x + xx[i] >= 1 && x + xx[i] <= n && y + yy[i] >= 1 && y + yy[i] <= n
						&& !vis[x + xx[i]][y + yy[i]] && map[x + xx[i]][y + yy[i]] == '0') {
					p.add(new Point(x + xx[i], y + yy[i]));
					step.add(s+1);
					vis[x + xx[i]][y + yy[i]] = true;//记得每次把可以走的坐标标记为走过
					if (x + xx[i] == x2 && y + yy[i] == y2) {
						System.out.println(s);
						return;
					}
				}
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/TXXERIN/article/details/107592092
今日推荐