Advertisement
neutrino2014

neutrino-portals

Sep 16th, 2014
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2.  
  3. class Portals
  4. {
  5.     static int rows;
  6.     static int cols;
  7.     static int[,] matrix;
  8.     static int[] dRow = new int[] {  0, 1, 0, -1 };
  9.     static int[] dCol = new int[] { -1, 0, 1,  0 };
  10.  
  11.     static void Main()
  12.     {
  13.         var xy = Console.ReadLine().Split(' ');
  14.         int startRow = int.Parse(xy[0]);
  15.         int startCol = int.Parse(xy[1]);
  16.  
  17.         var rc = Console.ReadLine().Split(' ');
  18.         rows = int.Parse(rc[0]);
  19.         cols = int.Parse(rc[1]);
  20.  
  21.         matrix = new int[rows, cols];
  22.         for (int row = 0; row < rows; row++)
  23.         {
  24.             var splitted = Console.ReadLine().Split(' ');
  25.             for (int col = 0; col < cols; col++)
  26.                 if (splitted[col] == "#")
  27.                     matrix[row, col] = -1;
  28.                 else
  29.                     matrix[row, col] = int.Parse(splitted[col]);
  30.         }
  31.  
  32.         Console.WriteLine(DFS(startRow, startCol));
  33.     }
  34.  
  35.     private static int DFS(int startRow, int startCol)
  36.     {
  37.         int power = matrix[startRow, startCol];
  38.  
  39.         if (power == 0) return 0;
  40.  
  41.         int maxSum = 0;
  42.         for (int i = 0; i < 4; i++)
  43.         {
  44.             int row = startRow + power * dRow[i];
  45.             int col = startCol + power * dCol[i];
  46.  
  47.             if (IsInsideMatrix(row, col) && matrix[row, col] != -1)
  48.             {
  49.                 matrix[startRow, startCol] = 0; // deactivate the teleport
  50.                 maxSum = Math.Max(maxSum, DFS(row, col));
  51.             }
  52.         }        
  53.  
  54.         // If teleport was used - add its power, else return 0;
  55.         maxSum = (matrix[startRow, startCol] == 0) ? maxSum + power : 0;
  56.  
  57.         matrix[startRow, startCol] = power; // re-activate the teleport
  58.  
  59.         return maxSum;
  60.     }
  61.  
  62.     private static bool IsInsideMatrix(int row, int col)
  63.     {
  64.         return row >= 0 && row < rows && col >= 0 && col < cols;
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement