Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package labirinth
- import java.io._
- import java.util.Scanner
- import scala.annotation.tailrec
- object Main {
- class TextFile(stream:InputStream) extends Iterable[String]{
- val scanner = new Scanner(stream)
- def iterator = new Iterator[String]{
- def hasNext = scanner.hasNextLine
- def next = scanner.nextLine
- }
- }
- case class Point(i:Int, j:Int){
- def +(that:Point) = Point(i+that.i,j+that.j)
- override def toString = "["+i+","+j+"]"
- def rotateClockWise = Point(j,-i)
- def rotateCouterWise = Point(-j,i)
- }
- class Labirinth(i:InputStream){
- val grid = new TextFile(i).map(x=>x.filter(_!=' ').toArray).toArray
- val max = Point(grid.size-1,grid(0).size-1)
- val start = grid.zipWithIndex.foldLeft(Point(-1,-1)){(acc,line)=>
- if(line._1.contains('X')) Point(line._2, line._1.indexOf('X')) else acc
- }
- def directionHelper(value:Int, maxValue:Int, fromZero:Int):Int = value match{
- case 0 => fromZero
- case x if x==maxValue => -fromZero
- case _ => 0
- }
- val startDirection = Point(directionHelper(start.i,max.i,-1),directionHelper(start.j,max.j,1))
- def canGo(position:Point) = grid(position.i)(position.j)=='.'
- @tailrec
- private def go(position:Point, direction:Point,way:List[Point]):List[Point] = position match {
- case q@(Point(0,_) | Point(_,0) | Point(max.i,_) | Point(_,max.j)) if q!=start => way
- case _ => {
- def rotation(p:Point):Stream[Point] = Stream.cons(p,rotation(p.rotateCouterWise))
- var newDirection = rotation(direction.rotateClockWise).find({x=>canGo(position+x)}).get
- go(position+newDirection, newDirection, position::way)
- }
- }
- def run = println(go(start, startDirection, List()).length)
- }
- def main(args: Array[String])= new Labirinth(new FileInputStream("input.txt")).run
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement