Time: O(n * m\!), Space: O(n * m\!)