time O(nm) space O(nm)