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