Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.9 kB
2
Indexable
package OnLuyen;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class MarioClimb {

	static int n, m, x_start, y_start, x_end, y_end, front, rear;
	static int[][] matrix = new int[55][55];
	static int[] queueX = new int[55 * 55 * 2];
	static int[] queueY = new int[55 * 55 * 2];
	static int[][] visit;
	static int[] dx = { -1, 0, 1, 0 };
	static int[] dy = { 0, 1, 0, -1 };

	static void input(Scanner sc) {
		n = sc.nextInt();
		m = sc.nextInt();
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				matrix[i][j] = sc.nextInt();
				if (matrix[i][j] == 2) {
					x_start = i;
					y_start = j;
				}
				if (matrix[i][j] == 3) {
					x_end = i;
					y_end = j;
				}
			}
		}
	}

	static int isOutOfCheck(int x, int y) {
		if (x < 0 || x >= n || y < 0 || y >= m) {
			return 1;
		}
		return 0;
	}

	static void push(int x, int y) {
		queueX[rear] = x;
		queueY[rear] = y;
		rear++;
	}

	static int find_h(int x, int y, int direct) {
		int h = 1;
		while (true) {
			if (isOutOfCheck(x + h * dx[direct], y) == 1 || matrix[x + h * dx[direct]][y] != 0) {
				break;
			}
			h++;
		}
		return h;
	}

	static void BFS() {
		int x, y, X, Y;
		while (front != rear) {
			x = queueX[front];
			y = queueY[front];
			for (int i = 0; i < 4; i++) {
				if (i == 0 || i == 2) {
					int h;
					h = find_h(x, y, i);
					X = h * dx[i] + x;
					Y = y + dy[i];
					if (isOutOfCheck(X, Y) == 0) {
						if (visit[X][Y] == 0) {
							if (visit[x][y] < h + 1) {
								visit[X][Y] = h + 1;
								push(X, Y);
							} else {
								visit[X][Y] = visit[x][y];
								push(X, Y);
							}
						} else {
							if (h + 1 > visit[x][y]) {
								if (h + 1 < visit[X][Y]) {
									visit[X][Y] = h + 1;
									push(X, Y);
								}
							} else {
								if (visit[x][y] < visit[X][Y]) {
									visit[X][Y] = visit[x][y];
									push(X, Y);
								}
							}
						}
					}
				} else {
					X = x + dx[i];
					Y = y + dy[i];
					if (isOutOfCheck(X, Y) == 0 && matrix[X][Y] != 0) {
						if (visit[X][Y] == 0) {
							visit[X][Y] = visit[x][y];
							push(X, Y);
						} else {
							if (visit[X][Y] > visit[x][y]) {
								visit[X][Y] = visit[x][y];
								push(X, Y);
							}
						}
					}
				}
			}
			front++;
		}
	}

	static void solve(int tc) {
		front = rear = 0;
		visit = new int[n][m];
		visit[x_start][y_start] = 1;
		push(x_start, y_start);
		BFS();
		System.out.println(visit[x_end][y_end]-1);
	}

	public static void main(String[] args) throws FileNotFoundException {
		System.setIn(new FileInputStream("MarioClimb.txt"));
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		for (int i = 0; i < T; i++) {
			input(sc);
			solve(i + 1);
		}
	}
}