在二维数组中查找元素的位置? [英] Finding position of an element in a two-dimensional array?
本文介绍了在二维数组中查找元素的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里的问题很简单(也许不是简单的答案?)
Well simple question here (maybe not a simple answer?)
假设我有一个二维数组
[0] [1] [2]
[3] [4] [5]
[6] [7] [8]
现在假设我想得到数字 6 的位置
Now suppose I want to get the position of the number 6
我知道对于一维数组我可以使用 Array.indexOf() 但是对于二维数组我有什么选择?
I know with a one-dimensional array i can use Array.indexOf() but what would my options be with 2-dimensional arrays?
谢谢!
推荐答案
我会这样说:
public static Tuple<int, int> CoordinatesOf<T>(this T[,] matrix, T value)
{
int w = matrix.GetLength(0); // width
int h = matrix.GetLength(1); // height
for (int x = 0; x < w; ++x)
{
for (int y = 0; y < h; ++y)
{
if (matrix[x, y].Equals(value))
return Tuple.Create(x, y);
}
}
return Tuple.Create(-1, -1);
}
这篇关于在二维数组中查找元素的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文