Advertisement
TeMePyT

MoveDownRightSum Algorithm

Jun 5th, 2018
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.58 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5.  
  6. namespace MoveDownRightSum
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             int[ , ] cells =
  13.             {
  14.                 {2, 6, 1, 8, 9, 4, 2},                           //You are given a matrix of numbers
  15.                 {1, 8, 0, 3, 5, 6, 7},                           //Find the largest sum of cells, starting from the top left corner
  16.                 {3, 4, 8, 7, 2, 1, 8},                           //Ending at the bottom right corner, going down or right each step.
  17.                 {0, 9, 2, 8, 1, 7, 9},                           //Задача от динамично оптимиране.
  18.                 {2, 7, 1, 9, 7, 8, 2},
  19.                 {4, 5, 6, 1, 2, 5, 6},
  20.                 {9, 3, 5, 2, 8, 1, 9},
  21.                 {2, 3, 4, 1, 7, 2, 8}
  22.             };
  23.              int[,] sums = new int[cells.GetLength(0), cells.GetLength(1)]; //Нова матрица, в която ще запазваме сумите от пътя до съответната клетка.
  24.             sums[0, 0] = cells[0, 0];
  25.             //Сумираме клетките в нулевия ред
  26.             for (int row = 1; row < sums.GetLength(0); row++)
  27.             {
  28.                 sums[row, 0] = sums[row - 1, 0] + cells[row, 0];
  29.             }
  30.             //Сумираме клетките  в нулевата колона
  31.             for (int col = 1; col < cells.GetLength(1); col++)
  32.             {
  33.                 sums[0, col] = sums[0, col - 1] + cells[0, col];
  34.             }
  35.             //Попълваме остатъка от матрицата със сумите
  36.             for (int row = 1; row < sums.GetLength(0); row++)
  37.             {
  38.                 for (int col = 1; col < sums.GetLength(1); col++)
  39.                 {
  40.                     //Взимаме по-голямата сума от тази отгоре и тази отляво+числото от матрицата за текущата клетка=сумата, която ще държи текущата клетка
  41.                     sums[row, col] = Math.Max(sums[row - 1, col], sums[row, col - 1]) + cells[row, col];
  42.                 }
  43.             }
  44.             var path = ReconstructPath(sums); //Погледнете метода най-отдолу
  45.             //Печат на попълнената матрица със суми(за онагледяване)
  46.             for (int row = 0; row < sums.GetLength(0); row++)
  47.             {
  48.                 for (int col = 0; col < sums.GetLength(1); col++)
  49.                 {
  50.                     if (path.Contains(new Tuple<int, int>(row, col))) //Ако хешсетът съдържа съответната клетка, оцветяваме в зелено
  51.                     {
  52.                         Console.ForegroundColor = ConsoleColor.Green;
  53.                     }
  54.                     Console.Write("{0, 3}", sums[row, col]);
  55.                     Console.ForegroundColor = ConsoleColor.White; // Връщаме цветът на бяло
  56.                 }
  57.                 Console.WriteLine();
  58.             }
  59.             Console.WriteLine();
  60.             //Печат на самата матрица
  61.             for (int row = 0; row < sums.GetLength(0); row++)
  62.             {
  63.                 for (int col = 0; col < sums.GetLength(1); col++)
  64.                 {
  65.                     if (path.Contains(new Tuple<int, int>(row, col)))
  66.                     {
  67.                         Console.ForegroundColor = ConsoleColor.Green;
  68.                     }
  69.                     Console.Write("{0, 3}", cells[row, col]);
  70.                     Console.ForegroundColor = ConsoleColor.White;
  71.                 }
  72.                 Console.WriteLine();
  73.             }
  74.         }
  75.         //Изграждаме пътя в обратен ред, от последната сума проверявайки накъде е по-голяма сумата
  76.         //(тоест подходящия път по който сме стигнали)  в хешсет.
  77.         private static HashSet<Tuple<int, int>> ReconstructPath(int[,] sums)
  78.         {
  79.             var path = new HashSet<Tuple<int, int>>();
  80.             int r = sums.GetLength(0) - 1;
  81.             int c = sums.GetLength(1) - 1;
  82.             path.Add(new Tuple<int, int>(r, c)); // Добавяме последната сума в хешсета
  83.             while (r > 0 && c > 0)
  84.             {
  85.                 if (sums[r - 1, c] > sums[r, c - 1])  //Ако сумата отляво е по-голяма, добавяме я в пътя
  86.                 {
  87.                     path.Add(new Tuple<int, int>(r - 1, c));
  88.                     r--;
  89.                 }
  90.                 else                                                        //В противен случай добавяме сумата отгоре
  91.                 {
  92.                     path.Add(new Tuple<int, int>(r, c - 1));
  93.                     c--;
  94.                 }
  95.             }
  96.             //Понеже вече сме стигнали или 0-та колона или 0-я ред, но може би не и края на пътя, попълваме остатъка(това което не е стигнало 0)
  97.             while (r > 0)
  98.             {
  99.                 path.Add(new Tuple<int, int>(r - 1, c));
  100.                 r--;
  101.             }
  102.             while (c > 0)
  103.             {
  104.                 path.Add(new Tuple<int, int>(r, c - 1));
  105.                 c--;
  106.             }
  107.             return path;
  108.         }
  109.     }
  110. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement