Поиск индекса нужного элемента - C#
Формулировка задачи:
Дан массив состоящий из 0 и 1. Как найти индекс единицы, которая находится ближе всего к 0(любому).Заранее спасибо.
Точнее берем любой 0,и нам нужно найти индекс ближайшей к нему единицы.
Решение задачи: «Поиск индекса нужного элемента»
textual
Листинг программы
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[,] arr = { { 0, 0, 0, 1, 0},
{ 1, 0, 0, 0, 1},
{ 0, 0, 1, 1, 0},
{ 1, 0 ,0, 0, 1} };
for (int i = 0; i < arr.GetLength(0); ++i)
{
for (int j = 0; j < arr.GetLength(1); ++j)
{
Console.Write("{0} ", arr[i, j]);
}
Console.WriteLine();
}
Console.Write("Введите (через пробел) индексы 0: ");
string[] ids0 = Console.ReadLine().Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
int id0i = Int32.Parse(ids0[0]);
int id0j = Int32.Parse(ids0[1]);
if (arr[id0i, id0j] != 0)
{
Console.WriteLine("На заданной позиции не находится 0.");
return;
}
int minDist = Int32.MaxValue;
int nearest1i = -1;
int nearest1j = -1;
for (int i = 0; i < arr.GetLength(0); ++i)
{
for (int j = 0; j < arr.GetLength(1); ++j)
{
if (arr[i, j] == 1)
{
int dist = Math.Abs(id0i - i) + Math.Abs(id0j - j);
if (dist < minDist)
{
minDist = dist;
nearest1i = i;
nearest1j = j;
}
}
}
}
Console.WriteLine("Индексы ближайшей к заданному нулю 1: {0}, {1}", nearest1i, nearest1j);
Console.WriteLine("Расстояние: {0}", minDist);
}
}
}