JAVA - DSF Example

 class Solution {


class Point{
int x ;
int y ;
int steps;
public Point(int x, int y , int steps){
this.x = x;
this.y = y;
this.steps = steps;
}
}

public int shortestPathBinaryMatrix(int[][] grid) {
//BFS //DFS
//BFS -> Shortest path
//DSA : Queue
if(grid[0][0] != 0){
return -1;
}

int [][] moves = new int[][]{{0,-1} , {0,1} , {1,0}, {-1,0} , {-1,-1},{-1, 1},{1,1},{1,-1}};
Stack<Point> queue = new Stack<>();
queue.push(new Point(0 , 0, 1));
grid[0][0] = 1;
int newX = 0;
int newY = 0;

while(! queue.isEmpty()){
Point point = queue.pop();

if(point.x == grid.length -1 && point.y == grid[0].length-1){
return point.steps;
}

for(int i = 0 ;i<8 ; i++){
newX = point.x + moves[i][0];
newY = point.y + moves[i][1];
if( newX >=0 && newY >=0 && newX < grid.length && newY < grid[0].length && grid[newX][newY] == 0){
queue.push(new Point(newX, newY , point.steps +1));
grid[newX][newY] = 1;
}
}
}
return -1;
}
}

/**
grid[i][i+1] = 0 ->
grid[i][i-1] = 0 <-
grid[i-1][i] = 0 A
grid[i+1][i] = 0 V

grid[i-1][i-1] = 0 <- A
grid[i-1][i+1] = 0 <- V
grid[i+1][i+1] = 0 -> V
grid[i+1][i-1] = 0 -> A
*/

留言

此網誌的熱門文章

MAP - Sort with stream