Advertisement
Guest User

Untitled

a guest
Dec 6th, 2014
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.68 KB | None | 0 0
  1. import scala.io.Source
  2. import java.io.PrintWriter
  3. import scala.collection.mutable.PriorityQueue
  4. import util.control.Breaks._
  5.  
  6. /* The solution object. **/
  7. object MatrixPath extends App  {
  8.   // Read the input file
  9.   val lines = Source.fromFile("in.txt").getLines
  10.  
  11.   val n = lines.next().toInt
  12.  
  13.   // a matrix of size NxN
  14.   val matrix: Array[Array[Int]] = Array.ofDim[Int](n, n)
  15.  
  16.   for (x <- 0 until matrix.size) {
  17.     val intArr = lines.next().split(" ")
  18.     for (y <- 0 until intArr.size) {
  19.       matrix(x)(y) = intArr(y).toInt
  20.     }
  21.   }
  22.  
  23.   class Node (val i: Int, val j: Int, val sum: Int) extends Ordered[Node] {
  24.     def compare(that: Node): Int = that.sum.compare(this.sum)
  25.   }
  26.  
  27.   val visited: Array[Array[Boolean]] = Array.ofDim(n, n)
  28.   val queue = new PriorityQueue[Node]()
  29.  
  30.   def visit(i: Int, j: Int, sum: Int) {
  31.     if (i < 0 || i >= n || j < 0 || j >= n || visited(i)(j)) {
  32.       return
  33.     }
  34.     queue.enqueue(new Node( i, j, sum+matrix(i)(j) ))
  35.     visited(i)(j) = true
  36.   }
  37.  
  38.   def findMinPathSum(): Int = {
  39.     var node: Node = new Node(0, 0, matrix(0)(0))
  40.  
  41.     queue.enqueue(node)
  42.  
  43.     breakable {
  44.     while (!queue.isEmpty) {
  45.       node = queue.head
  46.         if (node.i == n - 1 && node.j == n - 1) { break }
  47.  
  48.         visit(node.i + 1, node.j, node.sum)
  49.         visit(node.i - 1, node.j, node.sum)
  50.         visit(node.i, node.j + 1, node.sum)
  51.         visit(node.i, node.j - 1, node.sum)
  52.         queue.dequeue()
  53.       }
  54.     }
  55.     return node.sum
  56.   }
  57.  
  58.   val answer = findMinPathSum()
  59.   // Form and write the correct output
  60.   val writer = new PrintWriter("out.txt", "UTF-8")
  61.   try writer.print(answer.toString)
  62.   finally writer.close
  63. }
  64.  
  65. // EOF
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement