Facebook
From dani, 2 Months ago, written in Java.
Embed
Download Paste or View Raw
Hits: 190
  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.         Queue<Pair> q = new LinkedList<Pair>();
  24.         q.add(new Pair(0, 0));
  25.         long [][] d = new long [n][m];
  26.         for(int i = 0 ; i < n ; i++)
  27.             for(int j = 0 ; j < m ; j++)
  28.                 d[i][j] = 0;
  29.         Pair v;
  30.         boolean [][] ok = new boolean[n][m];
  31.         for(int i = 0 ; i < n ; i++)
  32.             for(int j = 0 ; j < m ;j++)
  33.                 ok[i][j] = false;
  34.         int x, y;
  35.         d[0][0] = 0;
  36.         ok[0][0] = true;
  37.         int [][] adj = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
  38.         while(!q.isEmpty()){
  39.             v = q.poll();
  40.             x = v.x;
  41.             y = v.y;
  42.             ok[x][y] = true;
  43.             for(int i = 0 ; i < 4 ; i++){
  44.                 if(!is_valid(x + adj[i][0], y + adj[i][1])) continue;
  45.                 if(a[x+adj[i][0]][y+adj[i][1]] == 1) continue;
  46.                 if(ok[x+adj[i][0]][y+adj[i][1]]) continue;
  47.                 d[x+adj[i][0]][y+adj[i][1]] = 1 + d[x][y];
  48.                 q.add(new Pair((x+adj[i][0]), (y+adj[i][1])));
  49.             }
  50.         }
  51.         for(int i = 0 ; i < n ;i++)
  52.             for(int j = 0 ; j < m ; j++)
  53.                 if(a[i][j] == 9)
  54.                     System.out.println(d[i][j]);
  55.     }
  56. }