time O(n*m*(n+m)) space O(n*m*(n+m))