洛谷P1683 Java解法

题目出处点这里
在这里插入图片描述
思路:从起点开始广搜,因为要求得出能走的最多的砖块数,所以每走一步就+1即可。

代码:

package search;

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

public class P1683 {

	static int W, H, x, y, sum = 1;
	static int[] xx = { 0, 0, 1, -1 };
	static int[] yy = { 1, -1, 0, 0 };
	static char[][] arr;
	static boolean[][] vis;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		W = sc.nextInt();
		H = sc.nextInt();
		arr = new char[H][W];
		vis = new boolean[H][W];
		for (int i = 0; i < H; i++) {
			String str = sc.next();
			arr[i] = str.toCharArray();
			if (str.contains("@")) {
				x = i;
				y = str.indexOf("@");
			}
		}
		bfs();
		System.out.println(sum);
	}

	public static void bfs() {
		Queue<Point> q = new LinkedList<Point>();
		q.add(new Point(x, y));
		vis[x][y] = true;
		while (!q.isEmpty()) {
			Point p = q.poll();
			for (int i = 0; i < 4; i++) {
				int row = p.x + xx[i];
				int col = p.y + yy[i];
				if (row >= 0 && row < H && col >= 0 && col < W && arr[row][col] != '#' && !vis[row][col]) {
					q.add(new Point(row, col));
					vis[row][col] = true;
					sum++;
				}
			}
		}
	}
}

猜你喜欢

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