You are given a matrix containing rows and columns and an integer .
Initially, all cells are assigned some value less or equal to . is the value of the row and column.
Each second all cell's value is increased by but it can increase maximum up to after that value of is unchanged.
On the second, you are at cell and want to go to cell.
At any point in time, you can jump to any adjacent cell. If you are at , then you can go to any of the adjacent cells, , , , and . You can move to the adjacent cells only on one condition :
You can move to any adjacent cell if and only if the value of the cell, where you are standing, is equal to the value of the adjacent cell and you can not go outside of the matrix
Note: Jump time is negligible
Your task is to determine the minimum time to reach from the cell.
Example:
Input: n=2, m=2, c=3, arr[][] = { { 2, 2 }, { 1, 3 } }
Output: 1
Approach
Java
import java.util.Objects;import java.util.TreeSet;public class StrangeMatrix {public static int n, m;public static long a[][], mt[][], c;final public static long inf = (long) 1e17;public static int d[] = new int[] { -1, 0, 1, 0, -1 };public static boolean ok(int x, int y) {return 0 <= x && x < n && 0 <= y && y < m;}public static void main(String[] args) {n = 2;m = 2;c = 3;mt = new long[n][m];a = new long[n][m];int arr[][] = { { 2, 2 }, { 1, 3 } };for (int i = 0; i < n; ++i) {for (int j = 0; j < m; ++j) {mt[i][j] = arr[i][j];a[i][j] = inf;}}TreeSet<Pair> Ts = new TreeSet<>();a[0][0] = 0l;Ts.add(new Pair(0l, 0, 0));while (!Ts.isEmpty()) {Pair cur = Ts.pollFirst();long tim = cur.a;int x = cur.fs;int y = cur.sc;// System.err.println(tim + " " + x + " " + y);for (int i = 0; i < 4; ++i) {int nx = x + d[i];int ny = y + d[i + 1];if (ok(nx, ny)) {long curn = Math.min(mt[x][y] + tim, c);long nxtn = Math.min(mt[nx][ny] + tim, c);long needtobe = Math.max(curn, nxtn);if (curn != nxtn)needtobe = c;long timr = Math.max(tim, Math.max(needtobe - mt[x][y], needtobe - mt[nx][ny]));if (timr < a[nx][ny]) {Ts.remove(new Pair(a[nx][ny], nx, ny));a[nx][ny] = timr;Ts.add(new Pair(a[nx][ny], nx, ny));}}}}System.out.println(a[n - 1][m - 1]);}static class Pair implements Comparable<Pair> {long a;int fs, sc;Pair() {}Pair(long a_, int fs_, int sc_) {a = a_;fs = fs_;sc = sc_;}@Overridepublic String toString() {return "Pair{" + "fs=" + fs + ", sc=" + sc + ", a=" + a + '}';}@Overridepublic int compareTo(Pair oth) {int ret = Long.compare(a, oth.a);if (ret != 0)return ret;ret = Integer.compare(fs, oth.fs);if (ret != 0)return ret;return Integer.compare(sc, oth.sc);}@Overridepublic boolean equals(Object o) {if (this == o)return true;if (!(o instanceof Pair))return false;Pair pair = (Pair) o;return a == pair.a && fs == pair.fs && sc == pair.sc;}@Overridepublic int hashCode() {return Objects.hash(a, fs, sc);}}}
No comments:
Post a Comment