/*
Question:
Calculate the minimum time from (0, 0) to (4, 4) path
Analysis:
This is a pure BFS question. However, to print the path, you can use an array to record the previous coordinate of the current coordinate,
Because BFS constructs a BFS optimal Spanning Tree, each node's parent node is unique.
ReferenceAlgorithmIntroduction...
*/
# Include <iostream>
# Include <cstring>
# Include <cstdio>
# Include <queue>
Using namespace STD;
# Define x 6
Int map [x] [X], pre [x] [x];
Bool visit [x] [x];
Struct Node
{
Int X, Y;
};
Void print (int x, int y) // print the path
{
If (X | Y) // recursive until (0, 0) at the beginning, and then output continuously to the path (4, 4 ).
Print (pre [x] [Y]/10, pre [x] [Y] % 10 );
If (pre [x] [Y]! =-1 & Pre [x] [Y]! =-1) // do not output the coordinates before (0, 0...
Printf ("(% d, % d) \ n", pre [x] [Y]/10, pre [x] [Y] % 10 );
}
Void BFS ()
{
Queue <node> q;
Node temp, cur;
Temp. x = 0;
Temp. Y = 0;
Q. Push (temp );
Int X, Y;
Visit [0] [0] = true;
While (! Q. Empty () // BFS Core
{
Cur = Q. Front ();
Q. Pop ();
X = cur. X;
Y = cur. Y;
If (x = 4 & Y = 4)
Print (4, 4 );
If (X &&! Visit [x-1] [Y] &! Map [x-1] [Y]) // go up
{
Visit [x-1] [Y] = true;
Temp. x = X-1;
Temp. Y = y;
Pre [x-1] [Y] = x * 10 + Y;
Q. Push (temp );
}
If (Y &&! Map [x] [Y-1] &! Visit [x] [Y-1]) // left
{
Visit [x] [Y-1] = true;
Temp. x = X;
Temp. Y = Y-1;
Pre [x] [Y-1] = x * 10 + Y;
Q. Push (temp );
}
If (Y <4 &&! Map [x] [Y + 1] &! Visit [x] [Y + 1]) // go to the right
{
Visit [x] [Y + 1] = true;
Temp. x = X;
Temp. Y = Y + 1;
Pre [x] [Y + 1] = x * 10 + Y;
Q. Push (temp );
}
If (x <4 &&! Map [x + 1] [Y] &! Visit [x + 1] [Y]) // go down
{
Visit [x + 1] [Y] = true;
Temp. x = x + 1;
Temp. Y = y;
Pre [x + 1] [Y] = x * 10 + Y;
Q. Push (temp );
}
}
}
Int main ()
{
Freopen ("sum. In", "r", stdin );
Freopen ("sum. Out", "W", stdout );
While (CIN> map [0] [0])
{
Memset (PRE,-1, sizeof (pre ));
Memset (visit, false, sizeof (visit ));
For (INT I = 0; I <5; I ++)
For (Int J = 0; j <5; j ++)
If (I | j)
Scanf ("% d", & map [I] [J]);
BFS ();
Printf ("(% d, % d) \ n",); // print the final Coordinate
}
Return 0;
}