距离最近的两个点之间的距离

import java.util.ArrayList;
import java.util.List;

//已知平面上的若干点的位置,存入一个List中。现在需要计算所有这些点中,
//距离最近的两个点间的最小距离。
public class Title4 {
	public static void main(String[] args){
		MyPoint mp1 = new MyPoint(1,2);
		MyPoint mp2 = new MyPoint(4,10);
		MyPoint mp3 = new MyPoint(-1,4);
		MyPoint mp4 = new MyPoint(3,9);
		ArrayList<MyPoint> lst = new ArrayList<MyPoint>();
		lst.add(mp1);
		lst.add(mp2);
		lst.add(mp3);
		lst.add(mp4);
		System.out.println("两个点之间最小的距离为:"+getMinDistance(lst));
	}
	
	// list 中有若干个点
	// 返回其中最小的点的距离
	public static double getMinDistance(ArrayList<MyPoint> lst){
		double r = lst.get(0).distance(lst.get(0),lst.get(1));
		int n = lst.size();
		for(int i=0;i<n;i++){
			for(int j=i+1;j<n;j++){
				MyPoint p1 = lst.get(i);
				MyPoint p2 = lst.get(j);
				
				double d = MyPoint.distance(p1, p2);
				if(d<r){	//每次取小的值
					r = d;
				}
			}
		}
		return r;
	}
}
class MyPoint{
	private double x; //横坐标
	private double y; // 纵坐标
	
	public MyPoint(double x,double y){
		this.x = x;
		this.y = y;
	}
	
	public static double distance(MyPoint p1,MyPoint p2){
		double dx = p1.x - p2.x;
		double dy = p1.y - p2.y;
		return Math.sqrt(dx*dx+dy*dy);  //两点之间的距离
	}
}

你可能感兴趣的:(ACM,最小距离,蓝桥杯,点)