Skip to content

Commit 2d2f237

Browse files
added Maze DP
1 parent e9558bd commit 2d2f237

File tree

2 files changed

+52
-2
lines changed

2 files changed

+52
-2
lines changed

src/main/scala/algorithms/dynamic/EditDistance.scala

+13-2
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@ def editDistance(X: Array[Char], Y: Array[Char]): (Array[Array[Int]], Int) = {
1515
for (i <- 0 until n - 1) {
1616
Edit(0)(i) = i
1717
}
18-
for (i <- 0 until m - 1) {
18+
for (i <- 1 until m) {
1919
Edit(i)(0) = i
2020

21-
for (j <- 0 until n - 1) {
21+
for (j <- 1 until n) {
2222
val ins: Int = Edit(i)(j - 1) + 1
2323
val del: Int = Edit(i - 1)(j) + 1
2424
var rep: Int = Int.MaxValue
@@ -33,3 +33,14 @@ def editDistance(X: Array[Char], Y: Array[Char]): (Array[Array[Int]], Int) = {
3333
}
3434
(Edit, Edit(m - 1)(n - 1))
3535
}
36+
37+
@main
38+
def editDistanceMain(): Unit = {
39+
val x: Array[Char] = Array('A', 'L', 'G', 'O', 'R', 'I', 'T', 'H', 'M')
40+
val y: Array[Char] = Array('A', 'L', 'T', 'R', 'U', 'I', 'S', 'T', 'I', 'C')
41+
42+
val (mat, res) = editDistance(x, y)
43+
mat.foreach(row => println(row.mkString(" ")))
44+
println(s" The shortest edit distance is : $res ")
45+
46+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package algorithms.dynamic
2+
3+
/// Maze Path Counting Algorithm
4+
/// Computes the number of unique paths from the top-left corner to the bottom-right
5+
/// of an n x m grid, moving only right or down.
6+
///
7+
/// Uses dynamic programming to store intermediate results in a 2D table.
8+
///
9+
/// Time Complexity: O(n * m), where n and m are the grid dimensions.
10+
def maze(n: Int, m: Int): (Array[Array[Int]], Int) = {
11+
val Mem: Array[Array[Int]] = Array.fill(n, m)(0)
12+
13+
for (i <- 0 until n) {
14+
Mem(i)(0) = 1
15+
}
16+
for (j <- 0 until m) {
17+
Mem(0)(j) = 1
18+
}
19+
20+
for (i <- 1 until n) {
21+
for (j <- 1 until m) {
22+
Mem(i)(j) = Mem(i - 1)(j) + Mem(i)(j - 1)
23+
24+
}
25+
}
26+
27+
(Mem, Mem(n - 1)(m - 1))
28+
}
29+
30+
@main
31+
def mazeMain(): Unit = {
32+
val n: Int = 18
33+
val m: Int = 6
34+
35+
val (mat, res) = maze(n, m)
36+
mat.foreach(row => println(row.mkString(" ")))
37+
println(s" The number of paths is: $res ")
38+
39+
}

0 commit comments

Comments
 (0)