{-
二重リスト見てたら目が回ったので後日やる
-}
import Control.Monad
import Data.List

readInt :: String -> Int
readInt = read

main = do
 [a,b] <- map readInt.words<$> getLine
 s <- map (map readInt.words)<$>replicateM a getLine
 
solve s a b = move list ++ scythe list'
 where 
  list = map (ps s) [1..a]
  list' = ts list
move [] = []
move ([a,b]:as) = [[a,b],[a,b+1]] ++ move as
ps x j= transpose [last k,last init k]
 where
  k = f (1,j) [] [] x 

--このfさあ
f (i,j) s d [] = s 
f (i,j) s d [a] = d
f (i,j) s d (a:b:x) | even a = a ++ f (i+1,j) s d (b:x)
 |otherwise = (a-1) ++ f (i+1,j) (s ++ i) (d ++ j) (b+1:x)
--右端を縦に薙ぐ
scythe [] = []
scythe ([a,b]:as) = [[a,b],[a+1,b]] ++ scythe as
ts x i b = transpose [last k,last init k]
 where
  k = g (i,b) [] [] x

g (i,j) s d [] = s
g (i,j) s d [a] = d
g (i,j) s d (a:b:x) | even 