Advertisement
Guest User

Untitled

a guest
Oct 10th, 2019
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.90 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5.  
  6. #define N 5           //tabla merete
  7.  
  8. void initMaze(int maze[N][N]){
  9.     int i, j;
  10.     srand(time(0));
  11.     for(i=0; i<N; i++)
  12.         for(j=0; j<N; j++)
  13.             maze[i][j] = rand()%2;
  14. }
  15.  
  16.  
  17. void printMaze(int maze[N][N]){
  18.     int i, j;
  19.     printf("|");
  20.     for(j=0; j<N*4-1; j++) printf("-");
  21.     printf("|\n");
  22.     for(i=0; i<N; i++){
  23.         for(j=0; j<N; j++){
  24.             printf("| %c ", maze[i][j]==1 ? '1' : ' ');
  25.         }
  26.         printf("|\n|");
  27.         for(j=0; j<N*4-1; j++) printf("-");
  28.         printf("|\n");
  29.     }
  30.    
  31. }
  32.  
  33.  
  34. int solveMaze(int maze[N][N], int solution[N][N], int row, int col){
  35.     if(row == N-1 && maze[row][col] == 1){ //elertuk az utolso sort, keszen vagyunk
  36.         solution[row][col] = 1;
  37.         return 1;
  38.     }
  39.     if(row >= 0 && row < N && col >= 0 && col < N && maze[row][col] == 1 && solution[row][col] != 1){
  40.         solution[row][col] = 1;
  41.         if(solveMaze(maze, solution, row+1, col)) return 1; //megprobaljuk lefele
  42.         if(solveMaze(maze, solution, row, col-1)) return 1; //megprobaljuk balra
  43.         if(solveMaze(maze, solution, row, col+1)) return 1; //megprobaljuk jobbra        
  44.         solution[row][col] = 0; //egyik lepes sem vezetett megoldasra
  45.     }
  46.     return 0;
  47. }
  48.  
  49.  
  50. int main(){
  51.     int maze[N][N], solution[N][N], i, j, startCol, solutionFound=0;
  52.     initMaze(maze);
  53.     for(startCol=0; startCol<N; startCol++){
  54.         for(i=0; i<N; i++) for(j=0; j<N; j++) solution[i][j] = 0;
  55.         if(maze[0][startCol] == 1 && solveMaze(maze, solution, 0, startCol)){
  56.             solutionFound = 1;
  57.             break;
  58.         }
  59.     }
  60.     printf("Labirintus:\n\n");
  61.     printMaze(maze);
  62.     if(solutionFound){
  63.         printf("\nEgy lehetseges megoldas:\n\n");
  64.         printMaze(solution);
  65.     }
  66.     else{
  67.         printf("\nNincs megoldas.\n\n");
  68.     }
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement