Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static int minDist(int rows, int cols, int[][] grid){
- int n = grid.length;
- if(n == 1){
- return grid[0][0] == 1? 1: -1;
- }
- int[] dx = new int[]{0, -1, 0, 1};
- int[] dy = new int[]{1, 0, -1, 0};
- boolean[][] visited = new boolean[rows][cols];
- Queue<int[]> q = new LinkedList<>();
- q.offer(new int[]{0, 0});
- visited[0][0] = true;
- int res = 0;
- while(!q.isEmpty()){
- int size = q.size();
- for (int i = 0; i < size; i++){
- int[] arr = q.poll();
- if(arr[0] == rows && arr[1] == cols){
- return -1;
- }
- if(grid[arr[0]][arr[1]] == 9){
- return res;
- }
- for(int j = 0; j < 4; j++){
- int nx = arr[0] + dx[j];
- int ny = arr[1] + dy[j];
- if(nx < 0 || nx >= rows || ny < 0 || ny >= cols || visited[nx][ny]){
- continue;
- }
- if(grid[nx][ny] == 0) continue;
- q.offer(new int[]{nx, ny});
- visited[nx][ny] = true;
- }
- }
- res++;
- }
- return -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement