import Data.Function
import Data.List

main = do
  [h, w] <- map read . words <$> getLine
  sequence (replicate h getLine) >>= 
    putStr . unlines . (flip (:) <*> show . length) . 
    map (unwords . map show) .
    path w .
    map (map read . words)

path w =  map (\(from, to) -> case (from `divMod` w, to `divMod` w) of 
            ((y0, x0), (y1, x1)) -> map (+ 1) [y0, x0, y1, x1]) . 
          moves . zip indexes . concat . 
          zipWith ($) (cycle [id, reverse]) where
  indexes = concat . zipWith ($) (cycle [id, reverse]) . block w $ [0 ..]
  moves [_] = []
  moves ((from, n) : (to, m) : xs) 
    | odd n     = (from, to) : moves ((to, m + 1) : xs)
    | otherwise = moves ((to, m) : xs)

  block n = takeWhile (not . null) . map fst . 
            iterate (splitAt n . snd) . splitAt n 

