作者:泱泱大国吴 | 来源:互联网 | 2023-10-09 20:25
一、题目
题目已经讲述查找输入点与点之间的最小距离,特别需要注意的是
可能存在多个点对都符合最短距离要求,因此需要全部输出;
比如(1,1) (2,2) (3,3)
这里就有两对点都符合(1,1) (2,2) 和 (2,2) (3,3)
二、代码
注意:
(1)实现输入格式(x,y)格式输入
(2)使用 Point 类型记录每个点
(3)使用 Map 接口下的:TreeMap 和 IdentifyMap
(4)Map 接口的类型是Map>
,其中Double表示距离,List
表示一对点集合:比如(3,{(1,1),(2,2)})
import java.awt.*;
import java.util.*;
import java.util.List;public class Root {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("请输入坐标的个数:");int numberOfPoints = input.nextInt();
Point[] points = new Point[numberOfPoints];
for (int i &#61; 0; i < numberOfPoints; i&#43;&#43;) {System.out.print("输入第" &#43; (i &#43; 1) &#43; "个点的坐标(x,y)&#xff1a;");String str1 &#61; input.next();String[] str2 &#61; str1.split(",");int p1 &#61; Integer.parseInt(str2[0]);int p2 &#61; Integer.parseInt(str2[1]);points[i] &#61; new Point(p1,p2);}
Map<Double, List<Point>> mapTree &#61; new TreeMap<>();Map<Double, List<Point>> mapIdentity &#61; new IdentityHashMap<>();
for (int i&#61;0;i<numberOfPoints-1;i&#43;&#43;){for (int j&#61;i&#43;1;j<numberOfPoints;j&#43;&#43;){double distanst &#61; distance(points[i],points[j]);
List<Point> allList &#61; new ArrayList<Point>();allList.add(points[i]);allList.add(points[j]);mapTree.put(distanst,allList);mapIdentity.put(distanst,allList);}}
double key &#61; mapTree.keySet().iterator().next();
for (Map.Entry<Double,List<Point>> me:mapIdentity.entrySet()){if (me.getKey()&#61;&#61;key){System.out.println(me.getKey() &#43; "--->" &#43; me.getValue());}}}public static double distance(Point p1,Point p2){return Math.sqrt(Math.pow((p1.x-p2.x),2) &#43; Math.pow((p1.y-p2.y),2));}
}
结果如图&#xff1a;