14 Mayıs 2012 Pazartesi

Maze Path Finder in C Recursively

Having a 12x12 maze, We start to wander a starting point until finding stop point. We move to up, down, left,right from starting point. If we couldn't find any solution we return -1.

#include <stdio.h>
#define SIZE 12

void show_maze(int maze[][SIZE])
{
 int i,j;
 printf("\n\n");
 for (i = 0; i < SIZE; i++)
 {
  for (j = 0; j < SIZE; j++)
   printf("%d\t", maze[i][j]);
  printf("\n");
 }
}

int wander_maze(int maze[][SIZE], int sr, int sc)
{
 if (maze[sr][sc] == 2 || maze[sr][sc] == 1) return -1;

 show_maze(maze);

 if ((maze[sr][sc] != 1) && (sr >= 0) && (sr < SIZE) &&
  (sc >= 0) && (sc < SIZE))
  {
   maze[sr][sc] = 2;
   if (wander_maze(maze, sr, sc - 1) == 0) return 0;
   if (wander_maze(maze, sr, sc + 1) == 0) return 0;
   if (wander_maze(maze, sr - 1, sc) == 0) return 0;
   if (wander_maze(maze, sr + 1, sc) == 0) return 0;
  } else
  {
   return -1;
  }
}

int main(int argc, char *argv[])
{
 int maze[SIZE][SIZE] =
 { {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} ,
   {1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1} ,
   {0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1} ,
   {1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1} ,
   {1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0} ,
   {1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1} ,
   {1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1} ,
   {1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1} ,
   {1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1} ,
   {1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1} ,
   {1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1} ,
   {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} };

 wander_maze(maze, 2, 0);
 return 0;
}

Hiç yorum yok:

Yorum Gönder