Advertisement
Guest User

Untitled

a guest
Mar 30th, 2015
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include<iostream>
  2. #include<cstdio>
  3. #include<cstdlib>
  4.  
  5. using namespace std;
  6. const int M=5;
  7.  
  8. int mtrx[M][M]= {1, 1, 1, 0, 0,
  9.                  1, 1, 1, 1, 1,
  10.                  0, 1, 1, 1, 0,
  11.                  1, 1, 1, 0, 0,
  12.                  0, 0, 1, 1, 1,
  13.                 };
  14.  
  15. int overflow=M*M;
  16. int legjobb = overflow;
  17. int legjobbmtrx[M][M];
  18. void backtrack(int x, int y, int steps, int aktualismtrx[][M])
  19. {
  20.  
  21.     if(x<0 || x>M-1 || y<0 || y>M-1) return;
  22.     if(steps>overflow || steps > legjobb) return;
  23.     steps++;
  24.     aktualismtrx[x][y] = 1;
  25.     if(x == M-1 || y == M-1){
  26.         if(steps < legjobb){
  27.             legjobb = steps;
  28.             for(int i = 0; i < M; ++i){
  29.                 for(int j = 0; j < M; ++j){
  30.                     legjobbmtrx[i][j] = aktualismtrx[i][j];
  31.                 }
  32.             }
  33.         }
  34.     }
  35.  
  36.     if(steps>overflow || steps > legjobb) return;
  37.  
  38.     if(mtrx[x+1][y] == 1) backtrack(x+1, y, steps, aktualismtrx);
  39.     if(mtrx[x][y+1] == 1) backtrack(x, y+1, steps, aktualismtrx);
  40.     if(mtrx[x-1][y] == 1) backtrack(x-1, y, steps, aktualismtrx);
  41.     if(mtrx[x][y-1] == 1) backtrack(x, y-1, steps, aktualismtrx);
  42. }
  43.  
  44. int main()
  45. {
  46.     int aktualismtrx [M][M];
  47.  
  48.     for(int i = 0; i < M; ++i)
  49.     {
  50.         for(int k = 0; k < M; ++k)
  51.             for(int j = 0; j < M; ++j)
  52.                 aktualismtrx[k][j] = 0;
  53.         if(mtrx[i][0] == 1)
  54.         {
  55.             backtrack(i,0,0,aktualismtrx);
  56.         }
  57.         for(int k = 0; k < M; ++k)
  58.             for(int j = 0; j < M; ++j)
  59.                 aktualismtrx[k][j] = 0;
  60.         if(mtrx[0][i] == 1)
  61.         {
  62.             backtrack(0,i,0,aktualismtrx);
  63.         }
  64.  
  65.     }
  66.  
  67.     for(int i = 0; i < M; ++i)
  68.     {
  69.         for(int j = 0; j < M; ++j)
  70.         {
  71.             cout<<legjobbmtrx[i][j]<<' ';
  72.         }
  73.         cout<<endl;
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement