Pregunta de entrevista de IBM

Magic Carpet question that was easy Leetcode question.