import Control.Arrow
import Data.List
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Debug.Trace

main :: IO ()
main = breads >>= main'
    where
        main' [h, w] = replicateM h breads >>= printRes . solve h w
        printRes = mapM_ (putStrLn . unwords . map show)

solve :: Int -> Int -> [[Int]] -> [[Int]]
solve h w = edit . concat . searchl (1, 1) Nothing
    where
        edit ps = [length ps] : ps

        searchl n@(nh, nw) (Just p@(ph, pw)) ((x : xs) : ys)
            | odd x = trace ("searchl: pathl" ++ show n ++ "," ++ show p) pathl n p : searchl (nh, nw + 1) Nothing (xs : ys)
            | otherwise = searchl (nh, nw + 1) (Just p) $ xs : ys
        searchl n@(nh, nw) _ ((x : xs) : ys)
            | odd x = searchl (nh, nw + 1) (Just (nh, nw)) $ xs : ys
            | otherwise = searchl (nh, nw + 1) Nothing $ xs : ys
        searchl (nh, _) Nothing (_ : ys) = searchl (nh + 1, 1) Nothing ys
        searchl (nh, _) p (_ : y : ys) = searchr (nh + 1, w) p (reverse y : ys)
        searchl _ _ _ = []

        searchr n@(nh, nw) (Just p@(ph, pw)) ((x : xs) : ys)
            | odd x = trace ("searchr: pathr" ++ show n ++ "," ++ show p) pathr n p : searchr (nh, nw - 1) Nothing (xs : ys)
            | otherwise = searchr (nh, nw - 1) (Just p) $ xs : ys
        searchr n@(nh, nw) _ ((x : xs) : ys)
            | odd x = searchr (nh, nw - 1) (Just (nh, nw)) $ xs : ys
            | otherwise = searchr (nh, nw - 1) Nothing $ xs : ys
        searchr (nh, _) p (_ : ys) = searchl (nh + 1, 1) p ys
        searchr _ _ _ = []

        pathl (th, tw) (sh, sw)
            | sh /= th && sw > tw = qs
            | sh /= th = [sh, sw, th, sw] : ps
            | otherwise = ps
            where
                ps = [[th, p, th, p + 1] | p <- [sw..(tw - 1)]]
                qs = build sw
                build x 
                    | x > tw = [sh, x, sh, x - 1] : build (x - 1)
                    | otherwise = [[sh, tw, th, tw]]

        pathr (th, tw) (sh, sw)
            | sh /= th && sw < tw = qs
            | sh /= th = [sh, sw, th, sw] : ps
            | otherwise = ps
            where
                ps = [[th, p, th, p - 1] | p <- [sw, (sw - 1)..(tw + 1)]]
                qs = build sw
                build x 
                    | x < tw = [sh, x, sh, x + 1] : build (x + 1)
                    | otherwise = [[sh, tw, th, tw]]


breads :: IO [Int]
breads = unfoldr (\s -> second (maybe B.empty snd . B.uncons) <$> B.readInt s) <$> B.getLine