[英]Print the values of the shortest path from any element to a given element in the matrix
Input data: number of rows, number of columns, and the point's coordinates输入数据:行数、列数和点的坐标
the named position will be given the value 0.命名位置将被赋予值 0。
note: indexing starts from 1 (bad practice, I know, but that's the requirement)注意:索引从 1 开始(不好的做法,我知道,但这是要求)
ie: for this input 4 5 1 1 this matrix will be generated:即:对于这个输入 4 5 1 1 这个矩阵将被生成:
0 1 2 3 4 0 1 2 3 4
1 2 3 4 5 1 2 3 4 5
2 3 4 5 6 2 3 4 5 6
3 4 5 6 7 3 4 5 6 7
I don't want the code, but if someone could give me a hint or something to help, it would be greatly appreciated!!我不想要代码,但如果有人能给我提示或帮助,我将不胜感激!! If code is easier than explaining a way to solve it, then please don't hesitate to post it.(C++) Edit: I got a solution, how could I make this faster?如果代码比解释解决它的方法更容易,那么请不要犹豫发布它。(C++) 编辑:我有一个解决方案,我怎样才能让它更快?
#include <iostream>
using namespace std;
int main()
{
int v[501][501], i, j, m, n, o, p;
cin >> m >> n >> o >> p;
for (i = o; i >= 1; i--)
v[i][p] = o - i;
for(i = o;i <= m; i++)
v[i][p] = i - o;
for(i = 1; i <= m; i++)
for(j = 1; j <= n; j++){
if(j < p)
v[i][j] = -j + p + v[i][p];
else if(j > p)
v[i][j] = j - p + v[i][p];
}
for(i = 1 ; i <= m; i++){
for(j = 1; j <= n; j++)
cout << v[i][j] << " ";
cout << '\n';
}
}
Try to draw the answer for a few examples and you will see a pattern that you can mimic.尝试通过几个例子得出答案,你会看到一个可以模仿的模式。
For example:例如:
5 5 3 3 5 5 3 3
4 3 2 3 4 4 3 2 3 4
3 2 1 2 3 3 2 1 2 3
2 1 0 1 2 2 1 0 1 2
3 2 1 2 3 3 2 1 2 3
4 3 2 3 4 4 3 2 3 4
By the way this is a standard question to solve with BFS.顺便说一下,这是使用 BFS 解决的标准问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.