'training'에 해당되는 글 1건

  1. 2020.10.01 [Algorithm Training] Minesweeper 지뢰찾기 맵 만들기 2
반응형


지뢰 찾기는 MXN 크기의 지뢰밭에서 모든 지뢰의 위치를 찾는 게임이다. 이 게임의 각 셀은 인접한 최대 8개의 셀 중 몇 개의 셀에 지뢰가 있는지 보여준다.


아래와 같이 맵의 크기를 입력하고 지뢰의 위치를 #로 입력하면 게임 맵을 작성해 주는 프로그램을 만들어 보자.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
 
using namespace std;
 
int main()
{
    int row, column;
 
    cout << "Enter minefield size(row column): ";
    cin >> row >> column;
 
    char** field = new char* [row];
    for (int i = 0; i < row; i++)
    {
        field[i] = new char[column];
        //memset(field[i], 0, sizeof(char) * (column));
    }
 
    char line[100];
 
    cout << "Enter minefield(# = mine): " << endl;
    for (int i = 0; i < row; i++)
    {
        cin >> line;        
        memcpy_s(field[i], column, line, strlen(line) > (unsigned)column ? column : strlen(line));
        // Invalid input prevention.
    }
 
    char** map = new char* [row];
    for (int i = 0; i < row; i++)
    {
        map[i] = new char[column];
        memset(map[i], '0'sizeof(char* (column));
    }
 
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < column; j++)
        {
            if (field[i][j] == '#')
            {
                map[i][j] = '#';
            }
            else
            {
                for (int k = i - 1; k < i + 2; k++)
                    for (int l = j - 1; l < j + 2; l++)
                        if (k > -1 && k < row && l > -1 && l < column && field[k][l] == '#')
                            map[i][j]++;
            }
        }
    }
 
    cout << endl << endl << "Minefield map: " << endl;
 
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < column; j++)
        {
            cout << map[i][j] << ' ';
        }
        cout << endl;
    }
 
    for (int i = 0; i < row; i++)
    {
        delete[] field[i];
    }
    delete[] field;
 
    for (int i = 0; i < row; i++)
    {
        delete[] map[i];
    }
    delete[] map;
 
    return 0;
}



알고리즘은 간단하다. 각 셀에서 주변의 모든 셀을 검사해 지뢰가 있으면 숫자를 증가 시킨다. 모서리에 위치한 셀은 주변 셀을 검사할 때 배열의 범위를 넘어가지 않도록 주의 한다.


실행 결과.


반응형
Posted by J-sean
: