Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.LinkedList;
- import java.util.Scanner;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.StringTokenizer;
- public class LA_MAGRID {
- public static void main(String[] args) throws IOException {
- Input read = new Input();
- int t = read.nextInt();
- while (t-- > 0) {
- int n = read.nextInt(), m = read.nextInt();
- int[][] map = new int[n][m];
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < m; j++) {
- map[i][j] = read.nextInt();
- }
- }
- LinkedList<int[]> q = new LinkedList<int[]>();
- int[] curr = { 0, 0, 1, 1 };
- q.addLast(curr);
- int[][] visitedSrc = new int[n][m];
- int[][] visitedCurr = new int[n][m];
- int min = Integer.MAX_VALUE;
- while (!q.isEmpty()) {
- curr = q.removeFirst();
- if (curr[0] == n - 1 && curr[1] == m - 1) {
- min = min < curr[2] ? min : curr[2];
- }
- if (curr[0] < n - 1) {
- int[] lo = new int[4];
- lo[0] = curr[0] + 1;
- lo[1] = curr[1];
- if (map[lo[0]][lo[1]] + curr[3] <= 0) {
- lo[2] = curr[2] + 1 - (map[lo[0]][lo[1]] + curr[3]);
- lo[3] = 1;
- } else {
- lo[2] = curr[2];
- lo[3] = curr[3] + map[lo[0]][lo[1]];
- }
- if ((visitedCurr[lo[0]][lo[1]] <= lo[3] || visitedSrc[lo[0]][lo[1]] >= lo[2]))
- q.addLast(lo);
- }
- if (curr[1] < m - 1) {
- int[] lo = new int[4];
- lo[0] = curr[0];
- lo[1] = curr[1] + 1;
- if (map[lo[0]][lo[1]] + curr[3] <= 0) {
- lo[2] = curr[2] + 1 - (map[lo[0]][lo[1]] + curr[3]);
- lo[3] = 1;
- } else {
- lo[2] = curr[2];
- lo[3] = curr[3] + map[lo[0]][lo[1]];
- }
- if ((visitedCurr[lo[0]][lo[1]] <= lo[3] || visitedSrc[lo[0]][lo[1]] >= lo[2]))
- q.addLast(lo);
- }
- }
- System.out.println(min);
- }
- }
- }
- class Input {
- BufferedReader bf;
- StringTokenizer st;
- public Input() throws IOException {
- bf = new BufferedReader(new InputStreamReader(System.in));
- st = new StringTokenizer(bf.readLine());
- }
- public String next() throws IOException {
- while (!st.hasMoreTokens() && bf.ready()) {
- st = new StringTokenizer(bf.readLine());
- }
- return st.hasMoreTokens() ? st.nextToken() : null;
- }
- public boolean hasNext() throws IOException {
- while (!st.hasMoreTokens() && bf.ready()) {
- st = new StringTokenizer(bf.readLine());
- }
- return st.hasMoreTokens();
- }
- public int nextInt() throws IOException {
- while (!st.hasMoreTokens() && bf.ready()) {
- st = new StringTokenizer(bf.readLine());
- }
- return st.hasMoreTokens() ? new Integer(st.nextToken()) : 0;
- }
- }
Add Comment
Please, Sign In to add comment