C++實現蠻力最近對演算法

UExplorer發表於2020-12-06
#include<iostream>
using namespace std;

void GetMinDistance(int x[], int y[],int n)
{
	int MinDis = 100;//初始化最短距離
	int index1, index2;//記錄點的座標
	for(int i=0;i<n-1;i++)
		for (int j = i + 1; j < n; j++)
		{
			int Dis = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);
			if (Dis < MinDis)
			{
				MinDis = Dis;
				index1 = i;
				index2 = j;
			}
		}
	cout << "最短的距離為:" << MinDis << endl;
	cout << "相隔最近的兩個點為:1(" << x[index1] << "," << y[index1] << ")  2(" << x[index2] << "," << y[index2] << ")" << endl;
}


int main()
{
	int n;
	int x[50];
	int y[50];
	cout << "輸入點的個數n:";
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cout << "輸入第"<<i+1<<"個點的座標(x,y):";
		cin >> x[i] >> y[i];
	}
	GetMinDistance(x, y, n);
	system("pause");
	return EXIT_SUCCESS;
}

執行結果
在這裡插入圖片描述

相關文章