c ++ maze

Maze

Description

Define a two-dimensional array:
int Maze [. 5] [. 5] = {
0,. 1, 0, 0, 0,
0,. 1, 0,. 1, 0,
0, 0, 0, 0, 0,
0,. 1, 1, 1, 0,
0, 0, 0, 1, 0
};

It represents a labyrinth, in which 1 represents the wall, 0 way to go, can only go sideways or vertically to go, can not go sideways, requiring programmed to find the shortest route from the top left to the bottom right corner.

Input

A 5 × 5 two-dimensional array, showing a maze. Ensure data has a unique solution.

Output

Left to bottom right shortest path, the format as shown in the sample.

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

Source

// -*- C++ -*-
//===----------------------------- he.cpp ---------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <iostream>
#include <cstring>

using namespace std;

int g[6][6];
bool used[6][6];
int sx = 0, sy = 0, ex = 4, ey = 4;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
struct Point {
    int x, y;
    int steps;
    int p[30];
} que[30], v, u, s;

void bfs() {
    s.x = sx;
    s.y = sy;
    s.steps = 0;
    s.p[s.steps] = 0;
    int f = 0, e = 0;
    que[e++] = s;
    used[sx][sy] = true;
    while (f <= e) {
        u = que[f++];
        if (u.x == ex && u.y == ey) {
            int xx = 0, yy = 0;
            cout << "(" << xx << ", " << yy << ")" << endl;
            for (int i = 1; i <= u.steps; ++i) {
                xx = xx + dx[u.p[i]];
                yy = yy + dy[u.p[i]];
                cout << "(" << xx << ", " << yy << ")" << endl;
            }
            return;
        }
        for (int i = 0; i < 4; ++i) {
            int nx = u.x + dx[i];
            int ny = u.y + dy[i];
            if (nx >= 0 && nx < 5 && ny >= 0 && ny < 5 && g[nx][ny] != 1 && !used[nx][ny]) {
                v.x = nx;
                v.y = ny;
                v.steps = u.steps + 1;
                for (int j = 0; j < u.steps; ++j) {
                    v.p[j] = u.p[j];
                }
                v.p[v.steps] = i;
                que[e++] = v;
                used[nx][ny] = true;
            }
        }
    }
}

int main() {
    for (int i = 0; i < 5; ++i) {
        for (int j = 0; j < 5; ++j) {
            cin >> g[i][j];
        }
    }
    memset(used, false, sizeof(used));
    bfs();
    return 0;
}
/*
 * input:
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

*/

Guess you like

Origin www.cnblogs.com/LJA001162/p/11440203.html