On stack and recursion solving maze and Maze shortest path problem __ data structure

Source: Internet
Author: User
Tags assert

First, the stack to achieve the maze problem:

Problem Description: Using a two-dimensional array simulation maze, where 1 for the wall, 0 for the path, using the Stack method to determine whether the maze has exits, the following figure is a simple simulation of the maze:


Thought:

1. First give the entry point, such as the above figure entry point coordinates {2,0};

2. Starting from the entry point, in its upper and lower four directions, if the path (value of 0), then go forward, and each access node into the stack (push) to save and mark the path traversed by 2;

3. When there is no access in four directions, then start backtracking, the stack saved nodes start pop, and each pop position marked 3, until in a position to find a new way, if there is no new road, the stack will eventually be empty, that is, the maze has no export;

4. When the stack is not empty, and as shown in the example above figure {9,2}, that is, its horizontal axis = row number-1, then find the maze exit, at this time the stack is stored in this pathway path.

Code implementation:

#include <iostream> #include <cstdlib> #include <assert.h> #include <stack> using namespace std;
Const size_t n=10;
	struct Pos {int _row;
int _col;

}; BOOL Cheakisaccess (int *maze,size_t n,pos Pos)//Determine if each walk is a path (stack) {if (maze[pos._row*n+pos._col]==0) && (pos._
	Row>=0&&pos._row<n) && (pos._col>=0&&pos._col<n)) {return true;
return false;
	BOOL Getmazepath (int *maze,size_t n,pos entry,stack<pos> &path)//stack method to determine whether the maze has exits {assert (maze); Pos Cur=entry;
	Cur saves the current position path.push (cur);  Pos next=cur;
		Next saves the next location while (!path.empty ()) {cur=path.top ();  maze[cur._row*n+cur._col]=2;
		Mark traversed the road if (cur._row==n-1)//Find a path {return true;
		//heuristics: up and down to determine whether there is a path//on next=cur;
		Next._row-=1;
			if (cheakisaccess (Maze,n,next)) {Path.push (next);
		Continue
		}//Right next=cur;
		Next._col+=1;
			if (cheakisaccess (Maze,n,next)) {Path.push (next);
		Continue
		}//Down next=cur; NexT._row+=1;
			if (cheakisaccess (Maze,n,next)) {Path.push (next);
		Continue
		}//Left next=cur;
		Next._col-=1;
			if (cheakisaccess (Maze,n,next)) {Path.push (next);
		Continue  } maze[cur._row*n+cur._col]=3;     If four directions have no access to the dead end of the marked 3 Path.pop ();
and backtracking} return false;  } void Getmaze (int *maze,size_t N)//Get Maze {FILE *fout=fopen ("MazeMap.txt", "R");
	Reads assert (fout) in a file;
		for (size_t i=0;i<n;++i) {for (size_t j=0;j<n;)
			{int value=fgetc (fout); if (value== ' 1 ' | |
				value== ' 0 ') {maze[i*n+j]=value-' 0 ';
			++j;
				else if (value==eof) {cout<< "Error (Maze)" <<endl;
				Fclose (Fout);
			Return
}} fclose (Fout); } void Printmaze (int *maze,size_t N)//print Maze {for (size_t i=0;i<n;++i) {for (size_t j=0;j<n;++j) {cout&lt
		;<maze[i*n+j]<< "";
	} cout<<endl;
	} void Testmaze () {int maze[n][n];
	Getmaze ((int*) maze,n);  Printmaze ((int*) maze,n);

	Print Maze cout<<endl; Stack<pos>
	Path   Pos entry={2,0};
	Entrance maze[entry._row][entry._col]=2;//Mark entrance first for 2//stack to find whether the maze has export Getmazepath ((int*) maze,n,entry,path);
	Printmaze ((int*) maze,n); cout<< "Whether the maze has access.

"<<!path.empty () <<endl;}
	int main () {Testmaze ();
	System ("pause");
return 0; }
The results show:



Save path in stack:



Second, recursive realization of the shortest path to the maze problem

Problem Description: There are several path paths in the maze, using recursion to solve the shortest path in the maze, the following maze diagram:


Thought:

1. Find the entry point, up and down, temptation, if the next position is 0 or if the next position value is greater than the original position value plus 1, it is represented as a path, if found access to the recursive call itself, each time mark its value for the previous value plus 1, and each position into the stack to save;


2. If the path will be found in the original stack saved to another empty stack ShortPath, the original stack pops, and recursive end return;


3. If the above figure returns to the position {6,7}, its left 0 is the path, at the beginning of the recursive call, call to {6,6}, the value becomes 18, its left position is 0 path, call to {6,5}, the value becomes 19, the next position value is not more than the original position value plus 1, this recursive end of the original path back;

4. Return to position {6,4}, its right position value is greater than {6,4} position value plus 1, for the path, where the recursive call begins, each time the next position value is greater than the original position value plus 1, and then find the second path;


5. At this time stack and shortpath number size comparison, if less than, then in the stack content at this time assigned to ShortPath;


6. The original stack pops again, recursion again end the original road return, finally to the entry point, the original stack is empty, ShortPath save path for the shortest path maze.


Code implementation:

BOOL Cheakisaccess (int *maze,size_t n,pos cur,pos Next)//determine if each walk is a path (recursive) {if (maze[next._row*n+next._col]==1) | | (next._row<0| | Next._row>=n) | | (next._col<0| |
	Next._col>=n)) {return false;
	} if (maze[next._row*n+next._col]==0) {return true;
	} if (maze[next._row*n+next._col]>maze[cur._row*n+cur._col]+1)//If Next position value is greater than cur position value plus 1 is represented as a new path {return true;
return false; } void Getmazepathr (int *maze,size_t n,pos entry,stack<pos> &path,stack<Pos> &shortpath)//
	The recursive method solves the shortest path {assert (maze);
	Pos Cur=entry;
	Path.push (cur);
	Pos next=cur; if (cur._row==n-1) {if (shortpath.empty) | |
		Path.size () <shortpath.size ())//The shortest path to the Shorytpath stack {shortpath=path;
		} path.pop ();
	Return
	}//Upper next=cur;
	Next._row-=1;  if (cheakisaccess (Maze,n,cur,next)) {maze[next._row*n+next._col]=maze[cur._row*n+cur._col]+1;	
	Each time the present value is marked as the previous value plus 1 getmazepathr ((int*) maze,n,next,path,shortpath);
	}//Right next=cur;
	Next._col+=1; if (Cheakisaccess (maze,n,cUr,next)) {maze[next._row*n+next._col]=maze[cur._row*n+cur._col]+1;
	Getmazepathr ((int*) maze,n,next,path,shortpath);
	}//Down next=cur;
	Next._row+=1;
		if (cheakisaccess (Maze,n,cur,next)) {maze[next._row*n+next._col]=maze[cur._row*n+cur._col]+1;
	Getmazepathr ((int*) maze,n,next,path,shortpath);
	}//Left next=cur;
	Next._col-=1;
		if (cheakisaccess (Maze,n,cur,next)) {maze[next._row*n+next._col]=maze[cur._row*n+cur._col]+1;
	Getmazepathr ((int*) maze,n,entry,path,shortpath);
} path.pop ();
	} void Testmaze () {int maze[n][n];
	Getmaze ((int*) maze,n);  Printmaze ((int*) maze,n);

	Print Maze cout<<endl;
	Stack<pos> path; Stack<pos> ShortPath;   (Recursive implementation) Save the shortest path Pos entry={2,0} in the stack; 
    Entrance maze[entry._row][entry._col]=2;//Mark entrance first for 2//recursive search Maze Shortest Path Getmazepathr ((int*) maze,n,entry,path,shortpath);
    Printmaze ((int*) maze,n); cout<< "Whether the maze has access. "<<!
Shortpath.empty () <<endl; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.