Resolving my urge of playing minesweeper for once and for all.
python -m venv venv
source venv/bin/activate
python -m pip install -r requirements.txt
python app.py
or if you want to compile ts code and run it
tsc && python app.py
Basic strategy consist of three steps: 1 check if number-cell already fulfils mine condition, if thats the case, then all neighbouring cells are 100% not mines 2 if it fails mine condition, then check how many free cells are there in the neighbourhood, if number of such cells is equal to a number of missing mines, then all neighbouring cells are 100% mines 3 Repeat until no more cells can be solved
Example:
- First we discover that mine is in the bottom left corner (Step 2)
- then based on second "1" determine that middle cell must be empty (Step 1)
- lastly right cell must be mine to satisfy first "1" and "2" (Step 2)
This strategy is simple, fast and effective. If you are lucky is already enough to solve the small board.
For the rest we need to solve system of equations for each perimeter separately. System of equations is constructed in a way that matrix A represents if number cell is adjacent to a mine, x is a vector of all unknown cells where mine can be present, b is a vector of all number cells, f is a vector of all flags and known mines adjacent to number cells.
Formally:
Unfortunately, matrix
- Apply basic strategy first to reduce number of unknowns
- Simplify the system of equations by converting it to Echelon form by Gaussian elimination. This would remove some of the equations that are redundant and would reduce number of unknowns. For example above, row echelon form would be:
and general solution is:
So we only need to check for solutions where
Once set of solutions is found, we need to check if they are consistent with each other. Go through each solution and find index for which all solutions are consistent (all solutions have 1 or 0 in that index). Map index to cell location and mark it as 100% mine or 100% empty.
For each other cells we can calculate probability of mine being in that cell based on how many possible arrangements are possible for a given board state.
Example of Probability map - red cells are mines, blue cells are empty everything in between is probability of mine being in that cell (light green is 50-50)
The right perimeter can have solutions with 3 to 6 mines, we need to evaluate each option and calculate number of arrangements. So in this example there are 37 detached cells (not part of any perimeter) and lets say number of undiscovered mines is 15. So for solutions that have 3 mines they have possible of