Day2-C- maze -POJ3984

The definition of 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

The shortest path left to bottom right, 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) 

Analysis: Simple seek BFS path problem, with an array of paths to find a better deal, directly on the code:
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, 1, -1};

int G[5][5], vis[5][5];

struct Node {
    int x, y, pre;
    Node(int _x = -1, int _y = -1, int _pre = -1):x(_x),y(_y),pre(_pre){}
} Nodes[100];

bool inside(int x, int y) {
    return x >= 0 && x < 5 && y >= 0 && y < 5;
}

void print(Node p) {
    if(p.pre != -1)
        print(Nodes[p.pre]);
    printf("(%d, %d)\n", p.x, p.y);
}

int main() {
    for (int i = 0; i < 5; ++i) {      // read in
        for (int j = 0; j < 5; ++j)
            scanf("%d", &G[i][j]);
    }
    int head = 0, rear = 0;
    Nodes[rear++] = Node(0, 0);
    while(head < rear) {                 //bfs
        Node tmp = Nodes[head++];
        if(vis[tmp.x][tmp.y])
            continue;
        vis[tmp.x][tmp.y] = 1;
        if(tmp.x == 4 && tmp.y == 4)
            print(Nodes[head - 1]);
        for (int i = 0; i < 4; ++i) {
            int nx = tmp.x + dx[i], ny = tmp.y + dy[i];
            if(inside(nx,ny) && !G[nx][ny] && !vis[nx][ny]) {     //prevent multiple entries
                Nodes[rear++] = Node(nx, ny, head - 1);
            }
        }
    }
    return 0;
}
View Code

 

Guess you like

Origin www.cnblogs.com/GRedComeT/p/11220809.html