Skip to content

Instantly share code, notes, and snippets.

@alexandru-calinoiu
Last active December 15, 2015 20:49
Show Gist options
  • Save alexandru-calinoiu/5321518 to your computer and use it in GitHub Desktop.
Save alexandru-calinoiu/5321518 to your computer and use it in GitHub Desktop.
using System;
using System.Globalization;
using System.Text;
public class MountainWalk
{
private string[] _areaMap;
private int _height;
public string[] AreaMap
{
get
{
return this._areaMap;
}
set
{
this._areaMap = value;
}
}
public int Height
{
get
{
return this._height;
}
set
{
this._height = value;
}
}
public class Position
{
private int _i;
private int _j;
public int I
{
get
{
return this._i;
}
set
{
this._i = value;
}
}
public int J
{
get
{
return this._j;
}
set
{
this._j = value;
}
}
public Position(int i, int j)
{
I = i;
J = j;
}
}
public int cellsVisited(string[] areaMap, int heightDifference)
{
Position position = new Position(0, 0);
int result = 0;
AreaMap = areaMap;
Height = heightDifference;
do
{
result++;
char oldValue = AreaMap[position.I][position.J];
MarkVisited(position);
position = this.MoveNext(oldValue, position);
if (position == null)
{
break;
}
}
while (true);
return result;
}
public Position MoveNext(char oldValue, Position position)
{
Position newPosition = new Position(position.I + 1, position.J);
if (CanMove(oldValue, newPosition))
{
return newPosition;
}
newPosition = new Position(position.I, position.J - 1);
if (CanMove(oldValue, newPosition))
{
return newPosition;
}
newPosition = new Position(position.I - 1, position.J);
if (CanMove(oldValue, newPosition))
{
return newPosition;
}
newPosition = new Position(position.I, position.J + 1);
if (CanMove(oldValue, newPosition))
{
return newPosition;
}
return null;
}
public bool CanMove(char oldValue, Position position)
{
return position.I >= 0 && position.J >= 0 && AreaMap.Length > position.I
&& AreaMap[position.I].Length > position.J && AreaMap[position.I][position.J] != 'x'
&& Math.Abs(
int.Parse(oldValue.ToString(CultureInfo.InvariantCulture))
- int.Parse(AreaMap[position.I][position.J].ToString(CultureInfo.InvariantCulture))) <= Height;
}
public void MarkVisited(Position position)
{
StringBuilder sb = new StringBuilder(AreaMap[position.I]);
sb[position.J] = 'x';
AreaMap[position.I] = sb.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment