//关键 栈是用来存一条通路的!
#include <iostream>
using namespace std;
int M , N ;
int Maze[1000][1000];
int fx, fy;
typedef struct
{
int incX, incY;
} Direction;
typedef struct
{
int x, y;
int di;
} Box;
class Stack
{
private:
Box* path;
int top;
public:
Stack();
~Stack();
void push(Box temp);
Box pop();
bool isEmpty();
bool isFull();
void displayPath();
class Empty {};
class Full {};
};
Stack::Stack()
{
top = -1;
path = new Box[M * N];
}
Stack::~Stack()
{
delete[] path;
}
void Stack::push(Box temp)
{
if (!isFull())
path[++top] = temp;
else
throw Full();
}
Box Stack::pop()
{
if (!isEmpty())
return path[top--];
else
throw Empty();
}
bool Stack::isEmpty()
{
return top == -1;
}
bool Stack::isFull()
{
return top == M * N - 1;
}
void Stack::displayPath()
{
int i = 0;
if (isEmpty())
throw Empty();
while (!isEmpty() && i <= top)
{
cout << path[i].y << " " << path[i].x << endl;
i++;
}
}
bool findPath( Direction direction[], Stack& s)
{
int x, y, di;
int line, col;
Box temp;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (Maze[i][j] == 3) {
Maze[i][j] = -1;
temp = { i,j,-1 };
s.push(temp);
break;
}
}
}
while (!s.isEmpty())
{
temp = s.pop();
x = temp.x;
y = temp.y;
di = temp.di + 1;
while (di < 4)
{
line = x + direction[di].incX;
col = y + direction[di].incY;
if (Maze[line][col] == 0||Maze[line][col]==4)//一定要写或后面这个
{
temp = { x,y,di };
s.push(temp);
x = line;
y = col;
Maze[line][col] = -1;
if (x == fx && y == fy) {
temp = { line,col,-1 };
s.push(temp);
return true;
}
else
di = 0;
}
else
di++;
}
}
return false;
}
int main()
{
cin >> N >> M;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
cin >> Maze[i][j];
}
}
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (Maze[i][j] == 4) {
fx = i;
fy = j;
}
}
}
Stack s;
Direction direction[4] = { {1,0},{0,-1},{-1,0},{0,1} };
if (findPath( direction, s))
{
s.displayPath();
}
else cout << "DON'T FIND" << endl;
}