Untitled

 avatar
unknown
plain_text
2 years ago
2.6 kB
4
Indexable
package oek12;

import java.security.DomainCombiner;
import java.util.Scanner;

class index {
	int row;
	int col;

	public index(int x, int y) {
		this.row = x;
		this.col = y;

	}
}

public class fastrobot {
	static index[] queue;

	static void push(index x) {
		rear++;
		queue[rear] = x;
	}

	static index pop() {
		front++;
		return queue[front - 1];
	}

	static boolean isempty() {
		if (front == rear + 1) {
			return true;
		}
		return false;
	}

	static int N, M, rear, front;
	static int[] dichchuyenrow = { -1, 0, 1, 0 };
	static int[] dichchuyencol = { 0, 1, 0, -1 };
	static char[][] map;
	static boolean[][] check;

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int T = scanner.nextInt();
		for (int t = 1; t <= T; t++) {
			M = scanner.nextInt();
			N = scanner.nextInt();
			check = new boolean[N][M];
			int cst = scanner.nextInt() - 1;
			int rst = scanner.nextInt() - 1;
			check[rst][cst] = true;
			index stIndex = new index(rst, cst);
			queue = new index[N * M];
			rear = -1;
			front = 0;
			push(stIndex);
			int ce = scanner.nextInt() - 1;
			int re = scanner.nextInt() - 1;
			map = new char[N][M];
			for (int i = 0; i < N; i++) {
				String string = scanner.next();
				for (int j = 0; j < M; j++) {
					map[i][j] = string.charAt(j);
				}
			}
			int time = 0;
			boolean check5 = false;
			while (!isempty() && !check5) {
				int pt = rear - front + 1;
				for (int i = 0; i < pt; i++) {
					if(check5) {
						break;
					}
					index in = pop();
					
					for (int q = 0; q < 4; q++) {
						if(check5) {
							break;
						}
						int currow = in.row;
						int curcol = in.col;
						while (true) {

							int nextr = currow + dichchuyenrow[q];
							int nextc = curcol + dichchuyencol[q];
							if(nextr>=0 && nextr<N && nextc >= 0 && nextc <M 
									&& map[nextr][nextc] == '0') {
								if(check[nextr][nextc] == false) {
									if(nextr == re &&  nextc == ce) {
										check5 = true;
										break;
									}
									index newin = new index(nextr, nextc);
									push(newin);
									check[nextr][nextc] = true;
								}
								else if(check[nextr][nextc] == true) {
									currow = nextr;
									curcol = nextc;
									continue;
								}
								currow = nextr;
								curcol = nextc;
								
							}
							else {
								break;
							}

						}
					}

				}
				time++;
			}
			if(!check5) {
				System.out.println("-1");
			}
			else {
				System.out.println(time);
			}
			

		}
	}

}
Editor is loading...
Leave a Comment