A-Maze

Title: A-Maze

Topic Description: stuff have a map to find sister paper the map. Map display, 0 can go, can not go 1 represents the upper left corner is the entrance to the lower right corner is the sister paper, these two positions to ensure zero. Now that we know the map, then stuff it is not difficult to find the sister paper, you compile a program, write stuff to find the shortest route sister paper.

Input: Input is a 5 × 5 two-dimensional array, just the two numbers 0,1, representation positions in FIG.

Output: a plurality of rows, represented by the shortest path from upper left to lower right corner coordinates sequentially passes, formatted as shown in the sample. Ensure data has a unique solution.

Note:
the coordinates (x, y) represents the x-y line column, row, column numbering starts from 0, and at the upper left corner as the origin.
Further note that, the coordinates of the comma-separated output should be a space.

Problem-solving ideas: the typical maze class of topics, where you can take advantage of the breadth-first search plus memory technology solutions (of course also be dfs). You may be provided by a structure, which records the last position of the position, after the last search to the target, can go back return path.

Code:

#include<iostream>
#include<queue>
#include<vector>
using namespace std;
struct node//要构建的结构体
{
    int x;
    int y;
    int pre;
    int now;
};
int d1[4]={0,1,-1,0},d2[4]={1,0,0,-1};
int a[5][5];
node h[25];
int main()
{
    int t;
    for(int i=0;i<5;i++)
    {
        for(int j=0;j<5;j++)
        {
            cin>>a[i][j];
        }
    }
    h[0].x=0,h[0].y=0,h[0].pre=-1,h[0].now=0;
    queue<node> q;
    q.push(h[0]);//广搜开始
    int k=1;
    while(!q.empty())
    {
        node m=q.front();
        q.pop();
        int x=m.x,y=m.y,x1,y1,Now=m.now;
        if(x==4&&y==4)
        {
            t=Now;
            break;
        }
        for(int i=0;i<4;i++)
        {
                x1=x+d1[i],y1=y+d2[i];
                if(x1<0||y1<0||x1>4||y1>4)
                {
                    continue;
                }else if(a[x1][y1]==1)
                {
                    continue;
                }
                a[x1][y1]=1;
                h[k].x=x1,h[k].y=y1,h[k].now=k,h[k].pre=Now;//记录
                q.push(h[k]);
                k++;
        }
    }
    vector<node> f;//保存到vector中
    while(t!=-1)
    {
        f.push_back(h[t]);
        t=h[t].pre;
    }
    for(int i=f.size()-1;i>=0;i--)
    {
        cout<<"("<<f[i].x<<", "<<f[i].y<<")"<<endl;//输出
    }
}
Published 15 original articles · won praise 0 · Views 234

Guess you like

Origin blog.csdn.net/qq_43653717/article/details/104634163