Найти особые элементы матрицы и их количество - C#
Формулировка задачи:
Дана матрица найти особые элементы матрицы и их количество. Считаю особым элементом, если от элемента справа стоят элементы больше его а слева меньше.
При вводе допустим массива 3 на 3 с элементами
1 2 3
4 5 6
7 8 9
Выводит количество 2. Но должно быть 3, не пойму где ошибка, голова кругом..
Так же если ввести массив побольше 5 на 5 , там вообще пропадает много особых элементов, выводит около 6, хотя их там намного больше.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace laba3
{
class Program
{
static void Main(string[] args)
{
int N, M, count = 0, i, j;
Console.Write("Введите количество строк: ");
N = Convert.ToInt32(Console.ReadLine());
Console.Write("Введите количество столбцов: ");
M = Convert.ToInt32(Console.ReadLine());
int[,] mas = new int[M, N];
bool fl = true;
Console.WriteLine("Введите элементы массива:");
for (i = 0; i < N; i++)
{
for (j = 0; j < M; j++) {
Console.Write("mas[" + i + "," + j + "]: ");
mas[i,j] = Convert.ToInt32(Console.ReadLine());
}
}
for ( int t = 0; t < N; t++ )
{
for ( int d = 1; d < (M - 1); d++)
{
fl = true;
for (i = 0; i < d; i++)
{
if(mas[ t,d] <= mas[ t,i ])
fl = false;
for(i = t + 1; i < M ; i++)
if(mas [ t,d ] >= mas [ t,i ])
fl = false;
if( fl )
count++;
}
}
}
Console.WriteLine("Количество особых элементов массива = " + count);
Console.WriteLine("Матрица: ");
for (i = 0; i < N; i++, Console.WriteLine())
{
for (j = 0; j < M; j++)
{
Console.Write(mas[i, j] + " ");
}
}
Console.WriteLine("Нажмите Enter для завершения работы программы..");
Console.ReadLine();
}
}
}Решение задачи: «Найти особые элементы матрицы и их количество»
textual
Листинг программы
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
int n = 3;
int m = 3;
int[,] array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
// int[,] array = { { 1, 3, 3 }, { 4, 6, 5 }, { 9, 8, 7 } };
Console.WriteLine("Заданная матрица");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write("\t{0} ", array[i, j]);
}
Console.WriteLine();
}
var elms = GetSpecialElementsCount(array);
Console.WriteLine("Число элементов = {0}",elms);
Console.ReadKey();
}
private static int GetSpecialElementsCount(int[,] array)
{
int count = 0;
for (int i = 0; i < array.GetLength(0); i++)
for (int j = 1; j < array.GetLength(1) - 1; j++)
if (IsSpecialElement(array, i, j))
count++;
return count;
}
private static bool IsSpecialElement(int[,] array, int i, int j)
{
if (array[i, j -1] < array[i, j] && array[i, j] < array[i, j +1])
return true;
return false;
}
}
}