GetPacManResult.cs

CSharp · Console

/Program.cs

using System;
					
public class Program
{
	public class Point
	{
		public int Row;
		public int Col;
		public Point(int row, int col)
		{
			this.Row = row;
			this.Col = col;
		}
	}
	
	public static int GetPacManResult(int N, int M, Point point)
	{
		if (point.Row < 0 || point.Row > N || point.Col < 0 || point.Col > M)
		{
			throw new Exception("Wrong input data");
		}

		int start = 0; int end = M - 1; // двигаться по строке будем от start до end
		int direction = 1; // направление движения Pac-Man по строке: 1 - слева направо, -1 - справа налево
		int pointsCount = 1; // счетчик сьеденных точек Pac-Man-ом

		for (int i = 0; i < N; i++)
		{
			// идем по строке либо до конца строки (j == end), либо до ее начала (j == 0)
			for (int j = start; j != end + direction; j += direction)
			{
				// дошли до искомой точки - выводим результат!
				if (i == (point.Row - 1) && j == (point.Col - 1))
				{
					return pointsCount;
				}
				pointsCount++; // Pac-Man сьедает очередную точку
			}

			direction *= -1; // меняем направление движения

			// меняем значения переменных start и end без использования вспомогательной переменной
			start = start ^ end;
			end = end ^ start;
			start = start ^ end;
		}

		return pointsCount;
	}	
	public static void Main()
	{
		Console.WriteLine("UniLecs");
		Console.WriteLine(string.Format("Answer = {0}", GetPacManResult(3, 3, new Point(2, 1)))); // 6
		Console.WriteLine(string.Format("Answer = {0}", GetPacManResult(5, 2, new Point(4, 2)))); // 7		
	}
}
;