C ++迷路

迷路

説明

二次元アレイを定義する:
[5]迷路INT [する。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
}。

それは1が壁を表している迷路を表し、どこへ行く0道、唯一の横に行くことができない、行くために横または縦方向に行くことができ、右下隅に左上から最短ルートを見つけるようにプログラムが必要となります。

入力

迷路を示す5×5の2次元配列。データは独自のソリューションを持っていることを確認してください。

出力

右下の最短経路、試料に示すようなフォーマットに任さ。

サンプル入力

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

サンプル出力

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

ソース

// -*- 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

*/

おすすめ

転載: www.cnblogs.com/LJA001162/p/11440203.html