import java.util.* ;
import java.io.*;
class Path
{
int x; int y; int z;
//z is the minimum distance required to reach grid element at index(x,y)
Path(int x, int y,int z)
{
this.x=x;
this.y=y;
this.z=z;
}
}
public class Solution {
public static int minimumPathSum(int[][] triangle, int n) {
// Write your code here.
for(int i=0;i<n;i++)
{
min
=Math.
min(minPathSum
(triangle,n
-1,i,n
),min
); }
return min;
}
public static int minPathSum(int[][] grid, int row1, int col1,int n) {
// int row=grid.length;
// int col=grid[0].length;
boolean[][] visited=new boolean[n][n];
int []dx={1,1};
int []dy={0,1};
PriorityQueue <Path> queue=new PriorityQueue<Path>((e,f)->(e.z-f.z));
queue.offer(new Path(0,0,grid[0][0]));
while(!queue.isEmpty())
{
Path temp=queue.poll();
if(temp.x==row1&&temp.y==col1)
return temp.z;
for(int i=0;i<2;i++)
{
int a=temp.x+dx[i];
int b=temp.y+dy[i];
if(a<0||a>=n||b<0||b>=n||visited[a][b]==true)
continue;
visited[a][b]=true;
queue.offer(new Path(a,b,temp.z+grid[a][b]));
}
}
return -1;
}
}
aW1wb3J0IGphdmEudXRpbC4qIDsKaW1wb3J0IGphdmEuaW8uKjsgCmNsYXNzIFBhdGgKewogICAgaW50IHg7IGludCB5OyBpbnQgejsKICAgIC8veiBpcyB0aGUgbWluaW11bSBkaXN0YW5jZSByZXF1aXJlZCB0byByZWFjaCBncmlkIGVsZW1lbnQgYXQgaW5kZXgoeCx5KQogICAgUGF0aChpbnQgeCwgaW50IHksaW50IHopCiAgICB7CiAgICAgICAgdGhpcy54PXg7CiAgICAgICAgdGhpcy55PXk7CiAgICAgICAgdGhpcy56PXo7CiAgICB9Cn0KcHVibGljIGNsYXNzIFNvbHV0aW9uIHsKICAgIHB1YmxpYyBzdGF0aWMgaW50IG1pbmltdW1QYXRoU3VtKGludFtdW10gdHJpYW5nbGUsIGludCBuKSB7CiAgICAgICAgLy8gV3JpdGUgeW91ciBjb2RlIGhlcmUuCiAgICAgICAgIGludCBtaW49SW50ZWdlci5NQVhfVkFMVUU7CiAgICAgICAgIGZvcihpbnQgaT0wO2k8bjtpKyspCiAgICAgICAgIHsKICAgICAgICAgICAgIG1pbj1NYXRoLm1pbihtaW5QYXRoU3VtKHRyaWFuZ2xlLG4tMSxpLG4pLG1pbik7CiAgICAgICAgIH0KICAgICAgICAgcmV0dXJuIG1pbjsKICAgIH0KICAgICBwdWJsaWMgc3RhdGljIGludCBtaW5QYXRoU3VtKGludFtdW10gZ3JpZCwgaW50IHJvdzEsIGludCBjb2wxLGludCBuKSB7CiAgICAgICAgLy8gaW50IHJvdz1ncmlkLmxlbmd0aDsKICAgICAgICAvLyBpbnQgY29sPWdyaWRbMF0ubGVuZ3RoOwogICAgICAgIGJvb2xlYW5bXVtdIHZpc2l0ZWQ9bmV3IGJvb2xlYW5bbl1bbl07CiAgICAgICAgaW50IFtdZHg9ezEsMX07CiAgICAgICAgaW50IFtdZHk9ezAsMX07CiAgICAgICAgUHJpb3JpdHlRdWV1ZSA8UGF0aD4gcXVldWU9bmV3IFByaW9yaXR5UXVldWU8UGF0aD4oKGUsZiktPihlLnotZi56KSk7CiAgICAgICAgcXVldWUub2ZmZXIobmV3IFBhdGgoMCwwLGdyaWRbMF1bMF0pKTsKICAgICAgICB3aGlsZSghcXVldWUuaXNFbXB0eSgpKQogICAgICAgIHsKICAgICAgICAgICAgUGF0aCB0ZW1wPXF1ZXVlLnBvbGwoKTsKICAgICAgICAgICAgCiAgICAgICAgICAgIGlmKHRlbXAueD09cm93MSYmdGVtcC55PT1jb2wxKQogICAgICAgICAgICByZXR1cm4gdGVtcC56OwogICAgICAgICAgICBmb3IoaW50IGk9MDtpPDI7aSsrKQogICAgICAgICAgICB7CiAgICAgICAgICAgICAgICBpbnQgYT10ZW1wLngrZHhbaV07CiAgICAgICAgICAgICAgICBpbnQgYj10ZW1wLnkrZHlbaV07CiAgICAgICAgICAgICAgICBpZihhPDB8fGE+PW58fGI8MHx8Yj49bnx8dmlzaXRlZFthXVtiXT09dHJ1ZSkKICAgICAgICAgICAgICAgIGNvbnRpbnVlOwogICAgICAgICAgICAgICAgdmlzaXRlZFthXVtiXT10cnVlOwogICAgICAgICAgICAgICAgcXVldWUub2ZmZXIobmV3IFBhdGgoYSxiLHRlbXAueitncmlkW2FdW2JdKSk7CiAgICAgICAgICAgIH0KICAgICAgICB9CiAgICAgICAgcmV0dXJuIC0xOwogICAgIH0KfQ==