A characterization of some graphs with metric dimension two