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