从矩阵找出距离K内的元件 [英] Finding elements within distance k from a matrix
问题描述
给定一个* n的矩阵和值k,我们如何找到所有的邻居每一个元素?
例如:在 4 * 4
基质,具有 K = 2
说矩阵是:
Given a n*n matrix and a value k, how do we find all the neighbors for each element?
for example: in a 4*4
matrix, with k=2
say matrix is :
[ 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16]
在那里这些值的位置的索引,邻居 1为1,2,3,5,6,9
。该值 3,6和9
来只是因为K = 2,并不会是那里,如果K值是= 1。
where these values are the indexes of the location, the neighbors for 1 are 1,2,3,5,6,9
. The values 3,6 and 9
come only because k =2 and wouldnt be there if k was = 1.
同样的6邻居将 1 2 3 5 6 7 8 9 10 11 14
能否请你帮我写AC code在C ++来实现这一点。
Can you please help me to write a c code to implement this in c++.
这是冯·诺依曼邻居的问题,请能有人实现它在C ++中。谢谢
It is the problem of von Neumann neighborhood, please can some one implement it in c++. Thanks
推荐答案
这应该做的伎俩对于k = 1。做小的改动,使之对于所有的k工作
This should do the trick for k=1. Make minor changes to make it work for all k
int width = 4;
int height = 4;
int k = 1;
int value = 2;
bool hasRight = (value % width != 0);
bool hasLeft = (value % width != 1);
bool hasTop = (value > 4);
bool hasBottom = (value < (height * width - width));
cout << value; // Always itself
if(hasRight == true) {
cout << value+1 << " "; // Right
if(hasTop == true) {
cout << value-width << " " << value-width+1 << " "; // Top and Top-right
}
if(hasBottom == true) {
cout << value+width << " " << value+width+1; // Bottom and Bottom-right
}
}
if(hasLeft == true) {
cout << value-1 << " "; // Left
if(hasTop == true) {
cout << value-width-1 << " "; // Top-left
}
if(hasBottom == true) {
cout << value+width-1 << " "; // Bottom-left
}
}
这篇关于从矩阵找出距离K内的元件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!