Skip to content

Instantly share code, notes, and snippets.

@jooyunghan
Created May 24, 2013 02:46
Show Gist options
  • Save jooyunghan/5640970 to your computer and use it in GitHub Desktop.
Save jooyunghan/5640970 to your computer and use it in GitHub Desktop.
DevDay MineSweeper Part 1
#include <iostream>
using namespace std;
const char CLOSED = '#';
const char MINE = '*';
const char EMPTY = '-';
const int row = 2;
const int col = 6;
char input[row][col] = {
{'1','1','1','1','1','1'},
{'#','#','#','#','#','#'}};
bool allOpen() {
for (int r = 0; r < row; r++) {
for (int c = 0; c < col; c++) {
if (input[r][c] == CLOSED) // closed
return false;
}
}
return true;
}
void openAround(int r0, int c0, char ch) {
for (int r = r0-1; r <= r0+1; r++) {
for (int c = c0-1; c <= c0+1; c++) {
if (r < 0 || c < 0 || r >= row || c >= col)
continue;
if (input[r][c] == CLOSED)
input[r][c] = ch;
}
}
}
void openAroundAsEmpty(int r, int c) {
openAround(r, c, EMPTY);
}
void openAroundAsMine(int r, int c) {
openAround(r, c, MINE);
}
int countAround(int r0, int c0, char ch) {
int count = 0;
for (int r = r0-1; r <= r0+1; r++) {
for (int c = c0-1; c <= c0+1; c++) {
if (r < 0 || c < 0 || r >= row || c >= col)
continue;
if (input[r][c] == ch)
count++;
}
}
return count;
}
int countMinesAround(int r, int c) {
return countAround(r, c, MINE);
}
int countClosedAround(int r, int c) {
return countAround(r, c, CLOSED);
}
bool tryOpenAround(int r, int c) {
if (!isdigit(input[r][c]))
return false;
int numOfMinesAround = input[r][c] - '0';
int numOfOpenMinesAround = countMinesAround(r, c);
int numOfClosedAround = countClosedAround(r, c);
if (numOfMinesAround - numOfOpenMinesAround == numOfClosedAround) {
openAroundAsMine(r, c);
return true;
} else if (numOfMinesAround == numOfOpenMinesAround && numOfClosedAround > 0) {
openAroundAsEmpty(r, c);
return true;
} else {
return false;
}
}
void open() {
for (int r = 0; r < row; r++) {
for (int c = 0; c < col; c++) {
if (tryOpenAround(r, c)) {
return;
}
}
}
// here! nothing to open deterministically
// then open randomly
}
void solve() {
while (!allOpen()) {
open();
}
}
int main() {
solve();
for (int r = 0; r < row; r++) {
for (int c = 0; c < col; c++) {
cout << input[r][c] << ' ';
}
cout << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment