Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- public struct XY
- {
- public XY(int x, int y)
- {
- this.x = x;
- this.y = y;
- }
- public int x, y;
- public int GetValue(int[,] arr)
- {
- return arr[x, y];
- }
- public override string ToString()
- {
- return x.ToString() + ", " + y.ToString();
- }
- }
- public class Program
- {
- public static void Main(String[] args)
- {
- int[,] arr = new int[,]
- {
- {2,5,1,0},
- {3,3,1,9},
- {4,4,7,8}
- };
- GetLongestPath(arr).ForEach(x => Console.WriteLine(x.GetValue(arr)));
- }
- public static List<XY> GetLongestPath(int[,] arr)
- {
- List<XY> longestPath = new List<XY>(), currentLongestPath;
- for (int x = 0; x < arr.GetLength(0); x++)
- for (int y = 0; y < arr.GetLength(1);y++)
- {
- currentLongestPath = new List<XY>(){new XY(x, y)};
- CalculateLongestPathFrom(arr, currentLongestPath);
- if (currentLongestPath.Count > longestPath.Count)
- longestPath = new List<XY>(currentLongestPath);
- }
- longestPath = new List<XY>(){new XY(1, 2)};
- CalculateLongestPathFrom(arr, longestPath);
- Console.WriteLine();
- return longestPath;
- }
- private static void CalculateLongestPathFrom(int[,] arr, List<XY> path)
- {
- XY last = path.Last();
- List<XY> neighbours = GetNeighbours(arr, last).FindAll(n => n.GetValue(arr) > last.GetValue(arr));
- if (neighbours.Count > 0)
- {
- List<XY> longestPath = new List<XY>(0);
- foreach (XY neighbour in neighbours)
- {
- List<XY> tmpPath = new List<XY>(path);
- tmpPath.Add(neighbour);
- CalculateLongestPathFrom(arr, tmpPath);
- if (tmpPath.Count > longestPath.Count)
- longestPath = new List<XY>(tmpPath);
- }
- path.Clear();
- foreach (var el in longestPath)
- path.Add(el);
- }
- }
- private static List<XY> GetNeighbours(int[,] arr, XY indexes)
- {
- List<XY> result = new List<XY>(2);
- if (indexes.x > 0)
- result.Add(new XY(indexes.x - 1, indexes.y));
- if (indexes.x < arr.GetLength(0) - 1)
- result.Add(new XY(indexes.x + 1, indexes.y));
- if (indexes.y > 0)
- result.Add(new XY(indexes.x, indexes.y - 1));
- if (indexes.y < arr.GetLength(1) - 1)
- result.Add(new XY(indexes.x, indexes.y + 1));
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement