Skip to content

Instantly share code, notes, and snippets.

@dmarjenburgh
Forked from skuro/gist:3286e7a53d4938437ed1
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmarjenburgh/13bd68eddea679d791c7 to your computer and use it in GitHub Desktop.
Save dmarjenburgh/13bd68eddea679d791c7 to your computer and use it in GitHub Desktop.
(ns minesweeper
(:require [clojure.math.combinatorics :as combo]
[clojure.pprint :refer [pp pprint]]))
;; Given R x C and number of mines M
;; Wrote a program that checks if there exists puzzle can be solved
;; with one single click!
;; Input
;; x (number of test cases)
;; Ri Ci Mi
;; Idea:
;; We identify three types of cells:
;; - Free cells are empty non-adjacent to a mine
;; - Mine-adjacent cells are empty, but adjacent to a mine
;; - Mine cells have a mine
;; If there are no free cells, then solvable iff there is 1 mine-adj cell
;; Otherwise, only solvable if all free cells are connected and all
;; mine-adjacent cells are adjacent to a free cell
(defn solvable? [rows cols mines] true)
(defn fill-grid [r-num c-num mine-positions]
(let [v (reduce (fn [acc pos]
(assoc acc pos :*))
(vec (repeat (* r-num c-num) :.)) mine-positions)]
(mapv vec (partition r-num v))))
(defn gen-grids [r-num c-num m-num]
(map (partial fill-grid r-num c-num)
(combo/combinations (range (* r-num c-num)) m-num) ))
(def neighbours (for [x [-1 0 1] y [-1 0 1] :when (not (= x y 0))]
[x y]))
(defn cell-type [row-index col-index grid]
(let [cell-value (get-in grid [row-index col-index])]
(if (= cell-value :*)
:mine
(if (= :* (some #{:*} (map (fn [[dx dy]]
(get-in grid [(+ row-index dy) (+ col-index dx)])) neighbours)))
:mine-adjacent
:free))))
(defn flood-fill [grid [start-row start-col :as start-pos]]
(let [ctype (cell-type start-row start-col grid)]
(loop [pos start-pos]
(if (= ctype (get-in grid pos))
(recur-over-neighbours)
quit))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment