最短移动距离

问题

[问题描述]

X星球居民小区的楼房全是一样的,并且按矩阵样式排列。其楼房的编号为1,2,3…
当排满一行时,从下一行相邻的楼往反方向排号。
比如:当小区排号宽度为6时,开始情形如下:

1 2 3 4 5 6
12 11 10 9 8 7
13 14 15 …

我们的问题是:已知了两个楼号m和n,需要求出它们之间的最短移动距离(不能斜线方向移动) 输入为3个整数w m n,空格分开,都在1到10000范围内要求输出一个整数,表示m n 两楼间最短移动距离。

[样例输入]

6 8 2

[样例输出]

4

[样例输入]

4 7 20

[样例输出]

5

算法

思路

只要算出某个房间所在的行数和列数就能算出最短距离:|column1-column2|+|row1-row2|

代码

#include <iostream>
#include <cmath>
using namespace std;
int* pos(int w,int n){
	int position[2]={0,0};
	int row=ceil(n/(double)w);
	int column=n%w;
	if(row%2==0){
		if(column==0){
			column=1;
		}
		else{
			column=w-column+1;
		}		
	}
	else{
		if(column==0){
			column=w;
		}
	}
	position[0]=row;
	position[1]=column;
	return position;
}
int main(){
	int w,m,n;
	cin>>w>>m>>n;
	cout<<abs(pos(w,m)[0]-pos(w,n)[0])+abs(pos(w,m)[1]-pos(w,n)[1])<<endl;
	return 1;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用蚁群算法最短路径的MATLAB GUI界面的示例: 1. 创建一个GUI界面,包括一个“开始”按钮、一个“停止”按钮、一个显示最短路径的文本框和一个绘制当前路径的图形窗口。 2. 当用户点击“开始”按钮时,程序将读取用户输入的起点和终点,并开始运行蚁群算法来寻找最短路径。 3. 在算法运行期间,程序将在图形窗口中绘制当前的路径。每当一只蚂蚁找到一条更短的路径时,程序将更新最短路径文本框中的内容。 4. 当用户点击“停止”按钮时,程序将停止算法的运行,并显示最终的最短路径。 下面是一个简单的伪代码来实现上述过程: ```matlab % 在GUI界面上创建“开始”和“停止”按钮以及文本框和图形窗口 % 当用户点击“开始”按钮时,运行以下代码: start_point = get_start_point_from_GUI; end_point = get_end_point_from_GUI; pheromone_matrix = initialize_pheromone_matrix; distance_matrix = calculate_distance_matrix; best_path = []; best_distance = Inf; while ~user_clicked_stop_button % 每只蚂蚁遵循蚁群算法进行移动 [ant_paths, ant_distances] = ant_colony_algorithm(pheromone_matrix, distance_matrix); % 更新信息素矩阵 pheromone_matrix = update_pheromone_matrix(pheromone_matrix, ant_paths, ant_distances); % 检查是否发现了更短的路径 [shortest_path, shortest_distance] = get_shortest_path_and_distance(ant_paths, ant_distances); if shortest_distance < best_distance best_path = shortest_path; best_distance = shortest_distance; update_GUI_with_best_path(best_path); end end % 当用户点击“停止”按钮时,显示最终的最短路径 display_best_path_in_GUI(best_path); ``` 需要注意的是,伪代码中的一些函数需要根据实际情况进行实现,如`get_start_point_from_GUI`和`get_end_point_from_GUI`将从GUI界面中获取用户输入的起点和终点,`ant_colony_algorithm`将实现蚁群算法的主要逻辑,`update_pheromone_matrix`将更新信息素矩阵,`get_shortest_path_and_distance`将返回所有蚂蚁路径中的最短路径和距离
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值