Compare commits

..

2 Commits

Author SHA1 Message Date
205784aebe MinesweeperMacaw solved 2026-04-10 19:32:33 -05:00
16832f6cea removed gitkeep 2026-04-04 20:35:10 -05:00
2 changed files with 115 additions and 0 deletions

View File

View File

@@ -0,0 +1,115 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class MinesweeperMacaw {
public static char[][] grid;
public static char[][] modGrid;
public static int unknowns = 0;
public static boolean solved = false;
public static HashMap<Integer, ArrayList<Integer>> unknownLocations = new HashMap<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int macaws = sc.nextInt();
grid = new char[size][size];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid.length; j++) {
grid[i][j] = sc.next().charAt(0);
if (grid[i][j] == '.') {
ArrayList<Integer> l = new ArrayList<>();
l.add(i);
l.add(j);
unknownLocations.put(unknowns, l);
unknowns++;
}
}
}
modGrid = new char[size][size];
for (int i = 0; i < size; i++) {
modGrid[i] = grid[i].clone();
}
if (unknowns != 0) {
placeMacaws(0, macaws);
}
printGrid(grid);
sc.close();
}
public static void placeMacaws(int index, int macawsLeft) {
if (macawsLeft == 0) {
if (valid(modGrid)) {
for (int i = 0; i < modGrid.length; i++) {
grid[i] = modGrid[i].clone();
}
solved = true;
}
return;
}
if (solved)
return;
if (index == unknowns) {
return;
}
int a = unknownLocations.get(index).get(0);
int b = unknownLocations.get(index).get(1);
modGrid[a][b] = 'M';
placeMacaws(index + 1, macawsLeft - 1);
modGrid[a][b] = '.';
placeMacaws(index + 1, macawsLeft);
}
public static boolean valid(char[][] input) {
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input[i].length; j++) {
char c = input[i][j];
if (Character.isDigit(c)) {
int val = c - '0';
int num = 0;
for (int m = -1; m < 2; m++) {
for (int n = -1; n < 2; n++) {
if (i + m >= 0 && i + m < input.length && j + n >= 0 && j + n < input[0].length) {
if (input[i + m][j + n] == 'M') {
num++;
}
}
}
}
if (num != val) {
return false;
}
}
}
}
return true;
}
public static void printGrid(char[][] input) {
for (int i = 0; i < input.length; i++) {
String out = "";
for (int j = 0; j < input[i].length - 1; j++) {
out = out + input[i][j];
out += " ";
}
out += input[i][input[i].length - 1];
System.out.println(out);
}
}
}