#include<bits/stdc++.h>
#define inf 1e9
#define MAXN 101
int dirX[]={1,0,-1,0};
int dirY[]={0,1,0, -1};
using namespace std;
int mat[1024][1024];
bool vis[1024][1024];
int main(){
    int a,b;
    cin >> a >> b;
    for(int i = 0; i<a;i++){
        for(int j = 0; j < b; j++){
            cin >> mat[i][j];
        }
    }
    memset(vis, 0, sizeof(vis));
    bool notVisited = true;
    int currentPosOfDir = 0;
    int currX = 0;
    int currY = 0;
    int num = a*b;
    cout << mat[0][0];
    vis[0][0] = true;
    while(notVisited){
        int x;
        int y;
        for(int i = currentPosOfDir; i < 4; i++){
            x= currX+dirX[i];
            y = currY+dirY[i];
            if(x < b && y < a && x >=0 && y >=0 && !vis[y][x]){
                notVisited = true;
                currentPosOfDir = i;
                currX = x;
                currY = y;
                vis[y][x] = true;
                num--;
                break;
            } else {
                notVisited = false;
            }
        }
        if(notVisited){
            cout << " " << mat[y][x];
        } else {
            if(num>1){
                currentPosOfDir = 0;
                notVisited = true;
            }
        }
    }
    cout << endl;
return 0;
}