Skip to content

Commit 1784e46

Browse files
committed
matric
1 parent 6460410 commit 1784e46

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/codingpuzzle/matrix.clj

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
(ns codingpuzzle.matrix
2+
(:import (clojure.lang PersistentQueue)))
3+
4+
;You are given an M by N matrix consisting of booleans that represents a board. Each True boolean represents a wall. Each False boolean represents a tile you can walk on.
5+
;
6+
;Given this matrix, a start coordinate, and an end coordinate, return the minimum number of steps required to reach the end coordinate from the start. If there is no possible path, then return null. You can move up, left, down, and right. You cannot move through walls. You cannot wrap around the edges of the board.
7+
;
8+
;For example, given the following board:
9+
;
10+
;[[f, f, f, f],
11+
;[t, t, f, t],
12+
;[f, f, f, f],
13+
;[f, f, f, f]]
14+
;and start = (3, 0) (bottom left) and end = (0, 0) (top left), the minimum number of steps required to reach the end is 7, since we would need to go through (1, 2) because there is a wall everywhere else on the second row.
15+
16+
(def t false)
17+
(def f true)
18+
19+
(def board [[f, f, f, f],
20+
[t, t, f, t],
21+
[f, f, f, f],
22+
[f, f, f, f]])
23+
24+
(def start [3, 0])
25+
(def end [0, 0])
26+
27+
(loop [paths (conj PersistentQueue/EMPTY [start])]
28+
(when-not (empty? paths)
29+
(let [path (peek paths)
30+
[x y] (last path)
31+
next-pos (->> [[(dec x) y] [(inc x) y] [x (dec y)] [x (inc y)]]
32+
(remove (set path))
33+
(filter #(get-in board %)))]
34+
(cond
35+
(some #{end} next-pos) (count path)
36+
(seq next-pos) (recur (apply conj (pop paths) (map #(conj path %) next-pos)))
37+
:else (recur (pop paths))))))
38+
; 7

0 commit comments

Comments
 (0)