Advertisement
SergeyPGUTI

11.2.1( Не правильно)

Apr 23rd, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.32 KB | None | 0 0
  1. public class Qwer {
  2.     public static void main(String args[])
  3.     {
  4.         Scanner sc=new Scanner(System.in);
  5.         //инициализация
  6.         int n,start,end;
  7.         Stack<Integer> q=new Stack<Integer>();
  8.         n=sc.nextInt();
  9.         int arr[][]=new int[n][n];//матрица смежности
  10.         int d[]=new int[n];//массив расстояний
  11.         boolean mark[]= new boolean[n];//отметки пройденных вершин
  12.         ArrayList<Integer> AdjList[]=new ArrayList[n];
  13.         for (int i=0;i<n;i++)
  14.         {
  15.             AdjList[i]=new ArrayList<Integer>();
  16.         }
  17.  
  18.         //ввод исходных
  19.  
  20.         for (int i=0;i<n;i++)
  21.             for(int j=0;j<n;j++)
  22.                 arr[i][j]=sc.nextInt();
  23.         for (int i=0;i<n;i++)
  24.             for (int j=0;j<n;j++)
  25.             {
  26.                 if (arr[i][j]!=0) AdjList[i].add(j);
  27.             }
  28.         start=sc.nextInt();
  29.         start--;
  30.         end=sc.nextInt();
  31.         end--;
  32.  
  33.         //
  34.         mark[start]=true;
  35.         q.push(start);
  36.  
  37.  
  38.  
  39.         while (!q.empty())
  40.         {
  41.             int v=q.pop();
  42.             for(int i=0;i<AdjList[v].size();i++)
  43.             {
  44.                    if (mark[AdjList[v].get(i)]==false)
  45.                    {
  46.                        d[AdjList[v].get(i)]=d[v]+1;
  47.                        mark[AdjList[v].get(i)]=true;
  48.                        q.push(AdjList[v].get(i));
  49.                    }
  50.             }
  51.         }
  52.         System.out.println(d[end]);
  53.  
  54.        //раскрутка пути
  55.         int v=end,dist=d[end];//v-текущая вершина
  56.         int way[]=new int[dist];//массив для записи пути
  57.         int wayInd=dist-1;//итерратор массива
  58.  
  59.         while(wayInd>=0)
  60.         {
  61.             for (int i=0;i<AdjList[v].size();i++)
  62.             {
  63.                 if (d[AdjList[v].get(i)]==dist-1) {
  64.                     way[wayInd]=v;
  65.                     v = AdjList[v].get(i);
  66.                     dist--;
  67.                     wayInd--;
  68.                     break;
  69.                 }
  70.             }
  71.         }
  72.         //вывод пути
  73.         System.out.print((start+1)+" ");
  74.         for (int i=0;i<d[end];i++) {
  75.             System.out.print((way[i]+1) + " ");
  76.         }
  77.         System.out.println();
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement