Facebook
From dani, 2 Months ago, written in Java.
Embed
Download Paste or View Raw
Hits: 198
  1. import java.util.*;
  2.  
  3. public class main {
  4.     public static class Pair {
  5.         public int x, y;
  6.         public Pair(int x, int y){
  7.             this.x = x;
  8.             this.y = y;
  9.         }
  10.     }
  11.     public static int n, m;
  12.     public static boolean is_valid(long x, long y){
  13.         return x < n && y < m && x >= 0 && y >= 0;
  14.     }
  15.     public static void main( String[] args ){
  16.         Scanner scanner = new Scanner(System.in);
  17.         n = scanner.nextInt();
  18.         m = scanner.nextInt();
  19.         long [][] a = new long[n][m];
  20.         for(int i = 0 ; i < n ; i++)
  21.             for(int j = 0 ; j < m ; j++)
  22.                 a[i][j] = scanner.nextInt();
  23.         LinkedList<Pair> q = new LinkedList<Pair>();
  24.         q.push(new Pair(0, 0));
  25.         long [][] d = new long [n][m];
  26.         Pair v;
  27.         boolean [][] ok = new boolean[n][m];
  28.         for(int i = 0 ; i < n ; i++)
  29.             for(int j = 0 ; j < m ;j++)
  30.                 ok[i][j] = false;
  31.         int x, y;
  32.         d[0][0] = 0;
  33.         ok[0][0] = true;
  34.         int [][] adj = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
  35.         while(!q.isEmpty()){
  36.             v = q.pop();
  37.             x = v.x;
  38.             y = v.y;
  39.             ok[x][y] = true;
  40.             for(int i = 0 ; i < 4 ; i++){
  41.                 if(!is_valid(x + adj[i][0], y + adj[i][1])) continue;
  42.                 if(a[x+adj[i][0]][y+adj[i][1]] == 1) continue;
  43.                 if(ok[x+adj[i][0]][y+adj[i][1]]) continue;
  44.                 d[x+adj[i][0]][y+adj[i][1]] = 1 + d[x][y];
  45.                 q.push(new Pair((x+adj[i][0]), (y+adj[i][1])));
  46.             }
  47.         }
  48.         for(int i = 0 ; i < n ;i++)
  49.             for(int j = 0 ; j < m ; j++)
  50.                 if(a[i][j] == 9)
  51.                     System.out.println(d[i][j]);
  52.     }
  53. }