O(mn)
final version