📜  扫雷求解器

📅  最后修改于: 2021-04-17 18:08:43             🧑  作者: Mango

给定尺寸为N * M的二维数组arr [] [] ,表示扫雷器矩阵,其中每个单元格包含一个范围为[0,9]的整数,表示其自身以及与之相邻的所有八个单元格的地雷数量,任务是解决扫雷,并发现矩阵中的所有地雷。在包含一个地雷的单元格上打印“ X” ,在所有其他空单元格上打印 _” 。如果无法解决扫雷车,则打印“ -1”

例子:

输入生成:要求解给定的扫雷器矩阵arr [] [] ,它必须是有效输入,即扫雷器矩阵必须可解。因此,输入矩阵是在generateMineField()函数中生成的。请按照以下步骤生成输入扫雷器矩阵:

  • 用于生成输入的输入是雷场NM的大小,以及雷场的概率P (或密度)。
  • 如果在雷区没有地雷和P等于100,如果所有的细胞在雷区地雷概率P等于0。
  • 为每个单元格选择一个随机数,如果随机数小于P ,则将地雷分配给网格,并生成布尔数组mines [] []
  • 约束求解器的输入是每个网格的状态,该网格对自身及其周围的八个单元的地雷进行计数。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
  
// Stores the number of rows
// and columns of the matrix
int N, M;
  
// Stores the final generated input
int arr[100][100];
  
// Direction arrays
int dx[9] = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
int dy[9] = { 0, 0, 0, -1, -1, -1, 1, 1, 1 };
  
// Function to check if the
// cell location is valid
bool isValid(int x, int y)
{
    // Returns true if valid
    return (x >= 0 && y >= 0
            && x < N && y < M);
}
  
// Function to generate a valid minesweeper
// matrix of size ROW * COL with P being
// the probablity of a cell being a mine
void generateMineField(int ROW, int COL, int P)
{
    // Generates the random
    // number every time
    srand(time(NULL));
  
    int rand_val;
  
    // Stores whether a cell
    // contains a mine or not
    int mines[ROW][COL];
  
    // Iterate through each cell
    // of the matrix mine
    for (int x = 0; x < ROW; x++) {
        for (int y = 0; y < COL; y++) {
            // Generate a random value
            // from the range [0, 100]
            rand_val = rand() % 100;
  
            // If rand_val is less than P
            if (rand_val < P)
  
                // MArk mines[x][y] as True
                mines[x][y] = true;
  
            // Otherwise, mark
            // mines[x][y] as False
            else
                mines[x][y] = false;
        }
    }
  
    cout << "Generated Input:\n";
  
    // Iterate through each cell (x, y)
    for (int x = 0; x < ROW; x++) {
        for (int y = 0; y < COL; y++) {
            arr[x][y] = 0;
  
            // Count the number of mines
            // around the cell (x, y)
            // and store in arr[x][y]
            for (int k = 0; k < 9; k++) {
                // If current adjacent cell is valid
                if (isValid(x + dx[k], y + dy[k])
                    && (mines[x + dx[k]][y + dy[k]]))
                    arr[x][y]++;
            }
  
            // Print the value at
            // the current cell
            cout << arr[x][y] << " ";
        }
        cout << endl;
    }
}
  
// Driver Code
int main()
{
    N = 7, M = 7;
    int P = 20;
  
    // Function call to generate
    // a valid minesweeper matrix
    generateMineField(N, M, 15);
}


CPP
// C++ program for the above approach
#include 
using namespace std;
  
// Stores the number of rows
// and columns in given matrix
int N, M;
  
// Maximum number of rows
// and columns possible
#define MAXM 100
#define MAXN 100
  
// Directional Arrays
int dx[9] = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
int dy[9] = { 0, 0, 0, -1, -1, -1, 1, 1, 1 };
  
// Function to check if the
// cell (x, y) is valid or not
bool isValid(int x, int y)
{
    return (x >= 0 && y >= 0
            && x < N && y < M);
}
  
// Function to print the matrix grid[][]
void printGrid(bool grid[MAXN][MAXM])
{
    for (int row = 0; row < N; row++) {
        for (int col = 0; col < M; col++) {
            if (grid[row][col])
                cout << "x ";
            else
                cout << "_ ";
        }
        cout << endl;
    }
}
  
// Function to check if the cell (x, y)
// is valid to have a mine or not
bool isSafe(int arr[MAXN][MAXM], int x, int y)
{
  
    // Check if the cell (x, y) is a
    // valid cell or not
    if (!isValid(x, y))
        return false;
  
    // Check if any of the neighbouring cell
    // of (x, y) supports (x, y) to have a mine
    for (int i = 0; i < 9; i++) {
  
        if (isValid(x + dx[i], y + dy[i])
            && (arr[x + dx[i]][y + dy[i]] - 1 < 0))
            return (false);
    }
  
    // If (x, y) is valid to have a mine
    for (int i = 0; i < 9; i++) {
        if (isValid(x + dx[i], y + dy[i]))
  
            // Reduce count of mines in
            // the neighboring cells
            arr[x + dx[i]][y + dy[i]]--;
    }
  
    return true;
}
  
// Function to check if there
// exists any unvisited cell or not
bool findUnvisited(bool visited[MAXN][MAXM],
                   int& x, int& y)
{
    for (x = 0; x < N; x++)
        for (y = 0; y < M; y++)
            if (!visited[x][y])
                return (true);
    return (false);
}
  
// Function to check if all the cells
// are visited or not and the input array
// is satisfied with the mine assignments
bool isDone(int arr[MAXN][MAXM],
            bool visited[MAXN][MAXM])
{
    bool done = true;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            done
                = done && (arr[i][j] == 0)
                  && visited[i][j];
        }
    }
  
    return (done);
}
  
// Function to solve the minesweeper matrix
bool SolveMinesweeper(bool grid[MAXN][MAXM],
                      int arr[MAXN][MAXM],
                      bool visited[MAXN][MAXM])
{
  
    // Function call to check if each cell
    // is visited and the solved grid is
    // satisfying the given input matrix
    bool done = isDone(arr, visited);
  
    // If the solution exists and
    // and all cells are visited
    if (done)
        return true;
  
    int x, y;
  
    // Function call to check if all
    // the cells are visited or not
    if (!findUnvisited(visited, x, y))
        return false;
  
    // Mark cell (x, y) as visited
    visited[x][y] = true;
  
    // Function call to check if it is
    // safe to assign a mine at (x, y)
    if (isSafe(arr, x, y)) {
  
        // Mark the position with a mine
        grid[x][y] = true;
  
        // Recursive call with (x, y) having a mine
        if (SolveMinesweeper(grid, arr, visited))
  
            // If solution exists, then return true
            return true;
  
        // Reset the position x, y
        grid[x][y] = false;
        for (int i = 0; i < 9; i++) {
            if (isValid(x + dx[i], y + dy[i]))
                arr[x + dx[i]][y + dy[i]]++;
        }
    }
  
    // Recursive call without (x, y) having a mine
    if (SolveMinesweeper(grid, arr, visited))
  
        // If solution exists then return true
        return true;
  
    // Mark the position as unvisited again
    visited[x][y] = false;
  
    // If no solution existx
    return false;
}
  
void minesweeperOperations(int arr[MAXN][MAXN], int N,
                           int M)
{
  
    // Stores the final result
    bool grid[MAXN][MAXM];
  
    // Stores whether the positon
    // (x, y) is visited or not
    bool visited[MAXN][MAXM];
  
    // Initialize grid[][] and
    // visited[][] to false
    memset(grid, false, sizeof(grid));
    memset(visited, false, sizeof(visited));
  
    // If the solution to the input
    // minesweeper matrix exists
    if (SolveMinesweeper(grid, arr, visited)) {
  
        // Function call to print the grid[][]
        printGrid(grid);
    }
  
    // No solution exists
    else
        printf("No solution exists\n");
}
  
// Driver Code
int main()
{
    // Given input
    N = 7;
    M = 7;
    int arr[MAXN][MAXN] = {
        { 1, 1, 0, 0, 1, 1, 1 },
        { 2, 3, 2, 1, 1, 2, 2 },
        { 3, 5, 3, 2, 1, 2, 2 },
        { 3, 6, 5, 3, 0, 2, 2 },
        { 2, 4, 3, 2, 0, 1, 1 },
        { 2, 3, 3, 2, 1, 2, 1 },
        { 1, 1, 1, 1, 1, 1, 0 }
    };
  
    // Function call to perform
    // generate and solve a minesweeper
    minesweeperOperations(arr, N, M);
  
    return 0;
}


输出:
Generated Input:
0 1 1 1 1 1 1 
1 3 3 3 2 2 1 
1 2 2 2 2 2 1 
1 2 2 2 1 1 0 
1 2 1 1 1 1 1 
1 3 2 2 1 1 1 
1 3 2 2 1 1 1

方法:可以使用回溯来解决给定的问题。这个想法是要遍历矩阵的每个单元格,根据邻近小区的可用信息,是否为该小区分配一个地雷
请按照以下步骤解决给定的问题:

  • 初始化一个矩阵,例如grid [] []visited [] [],以存储生成的网格并在遍历网格时保持对被访问单元的跟踪。将所有网格值初始化为false
  • 声明一个递归函数resolveMineSweeper()以接受数组arr [] []grid [] []visited [] []作为参数。
    • 如果访问了所有单元,并且为满足给定输入grid [] []的单元分配了一个地雷,则对于当前的递归调用返回true
    • 如果访问了所有单元格,但解决方案不满足输入grid [] ,则为当前递归调用返回false
    • 如果发现以上两个条件为假,则找到一个未访问的像元(x,y)并将(x,y)标记为已访问。
    • 如果可以将地雷分配给位置(x,y) ,请执行以下步骤:
      • grid [x] [y]标记为true
      • 将矩阵arr [] []中相邻单元(x,y)的mine数量减少1
      • 递归调用具有(x,y)有一个地雷的solveMineSweeper() ,如果返回true ,则存在解决方案。对于当前递归调用返回true
      • 否则,将位置(x,y)重置,即将grid [x] [y]标记为false ,并将矩阵arr [] []中相邻单元(x,y)的地雷数量增加1
    • 如果具有(x,y)没有我的函数的solveMineSweeper()函数返回true ,则意味着存在一个解决方案。从当前递归调用返回true
    • 如果以上步骤中的递归调用返回false,则表示该解决方案不存在。因此,从当前的递归调用中返回false
  • 如果函数resolveMineSweeper(grid,arr,Visited)返回的值为true ,则存在解决方案。打印矩阵grid [] []作为所需的解决方案。否则,打印“ -1”

下面是上述方法的实现:

CPP

// C++ program for the above approach
#include 
using namespace std;
  
// Stores the number of rows
// and columns in given matrix
int N, M;
  
// Maximum number of rows
// and columns possible
#define MAXM 100
#define MAXN 100
  
// Directional Arrays
int dx[9] = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
int dy[9] = { 0, 0, 0, -1, -1, -1, 1, 1, 1 };
  
// Function to check if the
// cell (x, y) is valid or not
bool isValid(int x, int y)
{
    return (x >= 0 && y >= 0
            && x < N && y < M);
}
  
// Function to print the matrix grid[][]
void printGrid(bool grid[MAXN][MAXM])
{
    for (int row = 0; row < N; row++) {
        for (int col = 0; col < M; col++) {
            if (grid[row][col])
                cout << "x ";
            else
                cout << "_ ";
        }
        cout << endl;
    }
}
  
// Function to check if the cell (x, y)
// is valid to have a mine or not
bool isSafe(int arr[MAXN][MAXM], int x, int y)
{
  
    // Check if the cell (x, y) is a
    // valid cell or not
    if (!isValid(x, y))
        return false;
  
    // Check if any of the neighbouring cell
    // of (x, y) supports (x, y) to have a mine
    for (int i = 0; i < 9; i++) {
  
        if (isValid(x + dx[i], y + dy[i])
            && (arr[x + dx[i]][y + dy[i]] - 1 < 0))
            return (false);
    }
  
    // If (x, y) is valid to have a mine
    for (int i = 0; i < 9; i++) {
        if (isValid(x + dx[i], y + dy[i]))
  
            // Reduce count of mines in
            // the neighboring cells
            arr[x + dx[i]][y + dy[i]]--;
    }
  
    return true;
}
  
// Function to check if there
// exists any unvisited cell or not
bool findUnvisited(bool visited[MAXN][MAXM],
                   int& x, int& y)
{
    for (x = 0; x < N; x++)
        for (y = 0; y < M; y++)
            if (!visited[x][y])
                return (true);
    return (false);
}
  
// Function to check if all the cells
// are visited or not and the input array
// is satisfied with the mine assignments
bool isDone(int arr[MAXN][MAXM],
            bool visited[MAXN][MAXM])
{
    bool done = true;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            done
                = done && (arr[i][j] == 0)
                  && visited[i][j];
        }
    }
  
    return (done);
}
  
// Function to solve the minesweeper matrix
bool SolveMinesweeper(bool grid[MAXN][MAXM],
                      int arr[MAXN][MAXM],
                      bool visited[MAXN][MAXM])
{
  
    // Function call to check if each cell
    // is visited and the solved grid is
    // satisfying the given input matrix
    bool done = isDone(arr, visited);
  
    // If the solution exists and
    // and all cells are visited
    if (done)
        return true;
  
    int x, y;
  
    // Function call to check if all
    // the cells are visited or not
    if (!findUnvisited(visited, x, y))
        return false;
  
    // Mark cell (x, y) as visited
    visited[x][y] = true;
  
    // Function call to check if it is
    // safe to assign a mine at (x, y)
    if (isSafe(arr, x, y)) {
  
        // Mark the position with a mine
        grid[x][y] = true;
  
        // Recursive call with (x, y) having a mine
        if (SolveMinesweeper(grid, arr, visited))
  
            // If solution exists, then return true
            return true;
  
        // Reset the position x, y
        grid[x][y] = false;
        for (int i = 0; i < 9; i++) {
            if (isValid(x + dx[i], y + dy[i]))
                arr[x + dx[i]][y + dy[i]]++;
        }
    }
  
    // Recursive call without (x, y) having a mine
    if (SolveMinesweeper(grid, arr, visited))
  
        // If solution exists then return true
        return true;
  
    // Mark the position as unvisited again
    visited[x][y] = false;
  
    // If no solution existx
    return false;
}
  
void minesweeperOperations(int arr[MAXN][MAXN], int N,
                           int M)
{
  
    // Stores the final result
    bool grid[MAXN][MAXM];
  
    // Stores whether the positon
    // (x, y) is visited or not
    bool visited[MAXN][MAXM];
  
    // Initialize grid[][] and
    // visited[][] to false
    memset(grid, false, sizeof(grid));
    memset(visited, false, sizeof(visited));
  
    // If the solution to the input
    // minesweeper matrix exists
    if (SolveMinesweeper(grid, arr, visited)) {
  
        // Function call to print the grid[][]
        printGrid(grid);
    }
  
    // No solution exists
    else
        printf("No solution exists\n");
}
  
// Driver Code
int main()
{
    // Given input
    N = 7;
    M = 7;
    int arr[MAXN][MAXN] = {
        { 1, 1, 0, 0, 1, 1, 1 },
        { 2, 3, 2, 1, 1, 2, 2 },
        { 3, 5, 3, 2, 1, 2, 2 },
        { 3, 6, 5, 3, 0, 2, 2 },
        { 2, 4, 3, 2, 0, 1, 1 },
        { 2, 3, 3, 2, 1, 2, 1 },
        { 1, 1, 1, 1, 1, 1, 0 }
    };
  
    // Function call to perform
    // generate and solve a minesweeper
    minesweeperOperations(arr, N, M);
  
    return 0;
}
输出:
_ _ _ _ _ _ _ 
x _ _ _ _ x _ 
_ x x _ _ _ x 
x _ x _ _ _ _ 
_ x x _ _ _ x 
_ _ _ _ _ _ _ 
_ x _ _ x _ _

时间复杂度: O(2 N * M * N * M)
辅助空间: O(N * M)