The program below is written in C and creates a stack that holds the values of a maze. This structure is beneficial during the development of a desktop game that uses a maze. Let me know if you find the code below helpful and if you have any additional suggestions:
Maze Runner Stack
#include <stdio.h>
#include <stdlib.h>
#define MAXSTACK 10
#define INTIAL 0
#define NORTH 1
#define EAST 2
#define SOUTH 3
#define WEST 4
int stack_maze[MAXSTACK][MAXSTACK];
int tmaze[10][10];
int rows,cols;
int startRow,startCol,endRow,endCol;
typedef struct{
int row,col;
int pos;
}StackEntry;
typedef struct stack{
int top;
StackEntry entry[MAXSTACK*MAXSTACK];
}Stack;
void Push(StackEntry item, Stack *ps){
ps->entry[ps->top++] = item;
}
// Pop: pop an item from the stack.
void Pop(StackEntry *item, Stack *ps){
*item = ps->entry[--ps->top];
}
// StackEmpty: returns non-zero if the stack is empty
int StackEmpty(Stack *ps){
return ps->top <= 0;
//other possible code is:
//return (ps->top == 0)
}
// StackFull: returns non-zero if the stack is full.
int StackFull(Stack *ps){
return ps->top >= MAXSTACK;
//other possible code is:
//return ps->top==MAXSTACK;
}
// CreateStack: initialize the stack to be empty.
void CreateStack(Stack *ps){
ps->top = 0;
}
void read_maze()
{
int i,j;
FILE *fptr=fopen("stack.txt","r");
fscanf(fptr,"%d %d",&rows,&cols);
for (j=0;j<=cols+1;j++)
tmaze[0][j]=tmaze[rows+1][j]=1;
for (i=1;i<=rows;i++)
tmaze[i][0]=tmaze[i][cols+1]=1;
for (i=1;i<=rows;i++)
for (j=1;j<=cols;j++)
tmaze[i][j]=0;
// startrting point startRow,startCol,stopRow,stopCol;
fscanf(fptr,"%d %d",&startRow,&startCol);
// ending point
while (fscanf(fptr,"%d %d",&i,&j)!=EOF)
{
tmaze[i][j]=1;
}
}
int maze_stack(int row,int col)
{
Stack s;
StackEntry entry;
int flag;
CreateStack(&s);
read_maze();
entry.row=row;entry.col=col;
entry.pos=INTIAL;
Push(entry,&s);
while (!StackEmpty(&s))
{
Pop(&entry,&s);
if (entry.pos==INTIAL)
{
if (stack_maze[entry.row][entry.col]!=0)
{
flag=0;
continue;
}
if (entry.row==endRow && entry.col==endCol)
{
stack_maze[entry.row][entry.col]=3;
flag=1;
continue;
}
stack_maze[entry.row][entry.col]=2;
}
else if (flag==1)
{
stack_maze[entry.row][entry.col]=3;
continue;
}
else if (entry.pos==WEST)
{
flag=0;
continue;
}
// Try next direction.
entry.pos++;
Push(entry,&s);
switch (entry.pos)
{
case NORTH: entry.row--; break;
case EAST: entry.col++; break;
case SOUTH: entry.row++; break;
case WEST: entry.col--; break;
}
entry.pos=INTIAL;
Push(entry,&s);
}
return 1;
}
Dani 4,329 The Queen of DaniWeb Administrator Featured Poster Premium Member
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.