이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

지뢰찾기

출처 : www.programming-challenges.com

지뢰찾기 게임은 M x N 매트릭스에 위치해 있는 지뢰를 찾는 게임이다.

M x N 매트릭스 상의 격자(square)는 지뢰이거나 지뢰가 아니다.

지뢰 격자는 *로 표시한다. 지뢰가 아닌 격자(square)는 숫자로 표시하며 그 숫자는 인접해 있는 지뢰의 수를 의미한다. (격자(sqaure)는 최대 8개의 인접한 지뢰를 가질 수 있다.)

다음은 4x4 매트릭스에서 2개의 지뢰(*)를 표시하는 방법이다.

*...
....
.*..
....

이 게임의 목표는 지뢰의 위치(*)를 제외한 나머지 격자들의 숫자를 맞추는 것이다.

위 경우의 답은 아래와 같다.

*100
2210
1*10
1110

입력

첫번째 줄은 M x N 의 M(행)과 N(열)에 해당되는 숫자이다. N과 M은 0보다 크고 100 이하이다. (0< N, M <=100) 그 다음 M개의 줄이 차례로 입력되고 각 줄은 정확하게 N개의 문자가 입력된다. 지뢰 격자는 *로 표시하며 지뢰가 아닌 격자는 .(dot)로 표시한다.

출력

지뢰(*)를 제외한 나머지 격자의 숫자값을 찾아서 M x N 매트릭스를 출력한다.


예1)

입력

4 4
*...
....
.*..
....

출력

*100
2210
1*10
1110

예2)

입력

3 5
**...
.....
.*...

출력

**100
33200
1*100

2014/03/07 01:26

pahkey

M,N 설명이 잘못되어 수정하였습니다. - Han Jooyung, 2016/12/05 15:02
지뢰위치는 제가 지정하는 건가요? random 하게 표시하는 건가요? - 예강효빠, 2017/06/04 12:07
@예강효빠님, 지뢰위치와 갯수는 임의로 입력하면 됩니다. - pahkey, 2017/06/05 09:29

104개의 풀이가 있습니다.

import random
m = int(input("M:"))
n = int(input("N:"))
if not(n > 0 and m <= 100):
    raise Exception("N > 0, M <= 100")
mn = [[random.choice(['.','.','.','.','*']) for x in range(n)] for y in range(m)]
for y in mn:
    print(''.join(y))
r = mn.copy()
for y, yd in enumerate(r):
    for x, xd in enumerate(yd):
        if r[y][x] == '*': continue
        count = 0
        c = [[''] if y - 1 < 0 else r[y-1][0 if x - 1 < 0 else x - 1:x+2],
             r[y][0 if x - 1 < 0 else x - 1:x+2],             
             [''] if y + 1 >= m else r[y+1][0 if x - 1 < 0 else x - 1:x+2]]
        for z in c:
            count+=z.count('*')
        r[y][x] = str(count)

print("output")
for y in r:
    print(''.join(y))    

Python 3.5.2에서 작성하였습니다.
M, N을 입력받고 지뢰 위치는 random으로 설정하였습니다.

2016/11/25 13:27

Yeo HyungGoo

(defn mine [input]
  (let [[m n & mines] (re-seq #"\S+" input)
        m (Integer/parseInt m)
        n (Integer/parseInt n)
        matrix (for [x (range 0 m), y (range 0 n)] [x y])
        mines (map #(re-seq #"." %) mines)
        mines (set (for [[x y] matrix]
                     (when (= (-> mines (nth x) (nth y)) "*")
                       [x y])))
        vincinity (for [u [-1 0 1], v [-1 0 1]] [u v])
        vincinity-of (fn [pos]
                       (map #(map + pos %) vincinity))
        check (fn [pos]
                (if (mines pos)
                  "*"
                  (str (count (keep mines (vincinity-of pos))))))
        result-matrix (partition n (map check matrix))]
    (with-out-str 
      (doseq [line result-matrix]
        (doseq [cell line]
          (print cell))
        (println)))))

Clojure 코드입니다.

풀이

그냥 루프 돌려서 주변 지뢰를 셌어요.

테스트

=> (mine "4 4\n*...\n....\n.*..\n....")
"*100\n2210\n1*10\n1110\n"

=> (mine "3 5\n**...\n.....\n.*...")
"**100\n33200\n1*100\n"

2014/03/07 17:34

박연오

자바입니다

package h26_mine;
import java.util.Scanner;
public class Mine {
public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    int N=in.nextInt(), M=in.nextInt(), i, j, ii, jj, n;
    char[][] boardC=new char[N][M]; //N,M 입력받아서 char boardC[N][M]을 만듦
    String[] boardS=new String[N];
    for(i=0;i<N;i++){ //입력
       boardS[i]=in.next(); //boardS[N]으로 String으로 입력받음
       for(j=0;j<M;j++) boardC[i][j]=boardS[i].charAt(j); //한글자씩 boardC[N][M]에 집어넣음
    }
    for(i=0;i<N;i++){ //연산 및 출력 함께
       for(j=0;j<M;j++)
       switch(boardC[i][j]){
       case '*' :
           System.out.print(boardC[i][j]); break;
       default :
           for(n=0, ii=(i>0)?i-1:0; ii<=i+1 && ii<=N-1; ii++)
               for( jj=(j>0)?j-1:0; jj<=j+1 && jj<=M-1; jj++)
                   if(boardC[ii][jj]=='*') n++; //동서남북대각선 8개칸에서 지뢰 세기
           System.out.print(n); break;
       }
       System.out.println();
    }
 }}

2014/03/09 15:46

Katherine

객체중심으로 설계하려다보니 소스코드가 좀 길게 나왔네요.. 음.. 맘에 들지는 않네요 ㅜㅜ.

  • Square 객체 : 포지션(x,y), 지뢰인지 아닌지 여부, 인접 지뢰갯수
  • Matrix 객체: M x N 만큼의 square를 지님, walk method로 지뢰를 검사, reveal method로 지뢰를 출력

파이썬입니다.

# -*- coding: utf-8 -*-
import unittest


class Square:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.value = 0
        self.isMine = False

    def __str__(self):
        if self.isMine: return "*"
        else: return "%s" % self.value


class Matrix:
    def __init__(self, src):
        self.map = []
        src = src.strip()
        lines = src.split("\n")
        for y, line in enumerate(lines):
            cols = []
            for x, s in enumerate(list(line)):
                square = Square(x, y)
                if s == '*': square.isMine = True
                cols.append(square)
            self.map.append(cols)

    def getSquare(self, x, y):
        if 0 <= x < len(self.map[0]) and 0 <= y < len(self.map):
            return self.map[y][x]
        else:
            return None

    def walk(self):
        direction = [
            (-1,-1),(0,-1),(1,-1),
            (-1,0),(+1, 0),
            (-1,+1),(0,+1),(1,+1),
        ]
        for row in self.map:
            for square in row:
                if not square.isMine: continue
                for dx, dy in direction:
                    next = self.getSquare(square.x+dx, square.y+dy)
                    if next: next.value += 1

    def reveal(self):
        result = []
        for row in self.map:
            for square in row:
                result.append(str(square))
            result.append("\n")
        return "".join(result).strip()


class MineTest(unittest.TestCase):
    def test1(self):
        matrix = Matrix("""
*...
....
.*..
....
        """)
        matrix.walk()
        self.assertEquals("""
*100
2210
1*10
1110
        """.strip(), matrix.reveal())

    def test2(self):
        matrix = Matrix("""
**...
.....
.*...
        """)
        matrix.walk()
        self.assertEquals("""
**100
33200
1*100
        """.strip(),  matrix.reveal())


if __name__ == "__main__":
    unittest.main()

2014/03/09 22:46

pahkey

% MATLAB
function dst = search_mine(src)
    % src : input mxn char array
    % dst : output mxn char array

    % convert logical(boolean) matrix
    mat = src == '*';
    % convolution kernel
    H = [1 1 1; 1 0 1; 1 1 1];

    t = conv2(double(mat),H,'same');

    dst = src;
    dst(~mat) = num2str(t(~mat));
end

핵심은 convolution!

2015/05/12 11:50

EiGeN

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_COLS 100000
void main() {
    FILE *f = fopen("input.txt", "rt");
    char s[MAX_COLS];
    int** board;

    int row  = 0;
    int col  = 0;
    int init = 1;
    int index = 0;
    while (fgets(s, MAX_COLS, f) != NULL) {
        if(init) {
            row = s[0]-48;
            col = s[2]-48;
            init = 0;
            board = (int**) malloc (sizeof(int*) * row);
            for(int i=0;i<row;i++)
                board[i] = (int*) malloc (sizeof(int) * col);
        }
        else {
            for(int i=0;i<col;i++)
                if(s[i]=='.')
                    board[index][i] = 0;
                else
                    board[index][i] = s[i];
            index++;
        }
    }

    for(int i=0;i<row;i++) {
        for(int j=0;j<col;j++) {
            if(board[i][j] == 42) {
                if(i-1 >= 0 && j+1 < col)
                    board[i-1][j+1]++;
                if(j+1 < col)
                    board[i][j+1]++;
                if(i+1 < row && j+1 < col)
                    board[i+1][j+1]++;

                if(i-1 >=0)
                    board[i-1][j]++;
                if(i+1 < row)
                    board[i+1][j]++;

                if(j-1 >= 0 && i-1 >= 0)
                    board[i-1][j-1]++;
                if(j-1 >= 0)
                    board[i][j-1]++;
                if(j-1 >= 0 && i+1 < row)
                    board[i+1][j-1]++;
            }
        }
    }



    for(int i=0;i<row;i++) {
        for(int j=0;j<col;j++) {
            if(board[i][j] == 42)
                printf("*");
            else
                printf("%d", board[i][j]);
        }
        printf("\n");
    }


    fcloseall();
}

2017/01/09 14:57

코딩초보

파이썬 2.7과 numpy, scipy 이용하였습니다.

import numpy as np
from scipy import signal

# Make mine map
y, x = 5, 5
mine = np.zeros((y, x))

r = np.random.randint(0, y, 2)
c = np.random.randint(0, x, 2)

mine[r, c] = 1

# Fine mine
kernel = np.ones((3, 3))

result = signal.convolve2d(mine, kernel, 'same')
result[r, c] = 0

print mine
print result

맵에서 1이 지뢰입니다. [[ 0. 0. 0. 0. 0.] [ 0. 0. 1. 0. 1.] [ 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0.]] ======================= 아래 결과는 주변 지뢰 개수입니다. [[ 0. 1. 1. 2. 1.] [ 0. 1. 0. 2. 0.] [ 0. 1. 1. 2. 1.] [ 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0.]]

2017/02/14 20:18

조현우

convolve2d 를 사용하실 생각을 하시다니~! 인상적입니다. - 예강효빠, 2017/06/06 05:40
from random import randint

def dice(tup):
    x,y=tup
    ng=randint(2, x*y)//2
    nglist=set()
    while len(nglist)<ng:
        nglist.add(tuple([randint(0, x-1), randint(0, y-1)]))
    return(sorted(list(nglist)), tup)

def findng(dc, firstmap):
    nglist=dc[0]
    x,y=dc[1]
    map2=list(firstmap)
    for i in range(x):
        map2[i]=map2[i].replace('.', '0')
    for i in range(x):
        for j in range(y):
            for a,b in nglist:
                if (a,b)!=(i,j) and map2[i][j].isdigit() and abs(a-i)<2 and abs(b-j)<2:
                    map2[i]=map2[i][:j]+str(int(map2[i][j])+1)+map2[i][j+1:]
    return(map2)

def where(dc):
    nglist=dc[0]
    x,y=dc[1]
    map1=[]
    for i in range(x):
        map1.append('.'*y)
        for a,b in nglist:
            if a==i:
                map1[i]=map1[i][:b]+'*'+map1[i][b:]
        map1[i]=map1[i][:y]
    map2=findng(dc, map1)
    map1='\n'.join(map1)
    map2='\n'.join(map2)
    return(map1, map2)

mn=tuple(map(int, input('m n: ').split()))

A=where(dice(mn))
print('{}\n\n{}'.format(A[0], A[1]))

2017/12/13 22:12

빗나감

파이썬 한달차 도전해봅니다.

import numpy as np
size = list(map(int, input('격자의 크기를 입력하세요. m*n -> m n : ').split()))
datas = []
if len(size) != 2:
    print('사이즈를 잘못 입력하셨습니다.')
    raise ValueError
else:
    m, n = size[0], size[1]
    count = 1
    while count <= m:
        data = list(input("%d번째 줄을 입력하세요. 지뢰는 '*', 지뢰가 아니면 '.'(dot) : " % count))
        if len(data) != n:
            print('잘못 입력하셨습니다.')
            raise ValueError
        elif set(data) - {'.', '*'}:
            print('잘못 입력하셨습니다.')
            raise ValueError
        else:
            datas.append(['.'] + data + ['.'])
            count += 1
    data = [['.' for x in range(n+2)]] + datas + [['.' for x in range(n+2)]]
mine = np.array(data)
for k in range(1, m+1):
    for j in range(1, n+1):
        if mine[k, j] == '*':
            pass
        else:
            mine[k, j] = [mine[k-1, j-1], mine[k-1, j], mine[k-1, j+1],
                          mine[k, j-1],                 mine[k, j+1],
                          mine[k+1, j-1], mine[k+1, j], mine[k+1, j+1]].count('*')
print(mine[1:m+1, 1:n+1])

결과

격자의 크기를 입력하세요. m*n -> m n : 5 5
1번째 줄을 입력하세요. 지뢰는 '*', 지뢰가 아니면 '.'(dot) : *****
2번째 줄을 입력하세요. 지뢰는 '*', 지뢰가 아니면 '.'(dot) : ...*.
3번째 줄을 입력하세요. 지뢰는 '*', 지뢰가 아니면 '.'(dot) : .....
4번째 줄을 입력하세요. 지뢰는 '*', 지뢰가 아니면 '.'(dot) : ..*..
5번째 줄을 입력하세요. 지뢰는 '*', 지뢰가 아니면 '.'(dot) : .....
[['*' '*' '*' '*' '*']
 ['2' '3' '4' '*' '3']
 ['0' '1' '2' '2' '1']
 ['0' '1' '*' '1' '0']
 ['0' '1' '1' '1' '0']]

2018/04/12 15:33

charming

import java.util.Scanner;
public class Mine {
public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    int N=in.nextInt(), M=in.nextInt(), i, j, ii, jj, n;
    char[][] boardC=new char[N][M]; //N,M 입력받아서 char boardC[N][M]을 만듦
    String[] boardS=new String[N];
    for(i=0;i<N;i++){ //입력
       boardS[i]=in.next(); //boardS[N]으로 String으로 입력받음
       for(j=0;j<M;j++) boardC[i][j]=boardS[i].charAt(j); //한글자씩 boardC[N][M]에 집어넣음
    }
    for(i=0;i<N;i++){ //연산 및 출력 함께
       for(j=0;j<M;j++)
       switch(boardC[i][j]){
       case '*' :
           System.out.print(boardC[i][j]); break;
       default :
           for(n=0, ii=(i>0)?i-1:0; ii<=i+1 && ii<=N-1; ii++)
               for( jj=(j>0)?j-1:0; jj<=j+1 && jj<=M-1; jj++)
                   if(boardC[ii][jj]=='*') n++; //동서남북대각선 8개칸에서 지뢰 세기
           System.out.print(n); break;
       }
       System.out.println();
    }
 }

2018/05/14 15:47

聂金鹏

파이썬 코딩도장 책으로 배우고 있습니다 아직 못배운 다른 방법들이 많이 보여서 신기하네요

col,row=map(int,input().split())
matrix=[]
for i in range(row):
    matrix.append(list(input()))
for x in range(row):
    for y in range(col):
        if matrix[x][y] == '*':
            print(matrix[x][y],sep='',end='')
        else:
            count = 0
            for xo in range(-1,2):
                for yo in range(-1,2):
                    if 0<=x+xo<row and 0<=y+yo<col and matrix[x+xo][y+yo] == '*':
                            count += 1
            print(count,sep='',end='')
    print()

2019/04/29 15:54

Van Stephen

def adjacents(crd)
    [
        [ crd[0] - 1, crd[1] - 1],
        [ crd[0] - 1, crd[1]    ],
        [ crd[0] - 1, crd[1] + 1],
        [ crd[0]    , crd[1] - 1],
        [ crd[0]    , crd[1]    ],
        [ crd[0]    , crd[1] + 1],
        [ crd[0] + 1, crd[1] - 1],
        [ crd[0] + 1, crd[1]    ],
        [ crd[0] + 1, crd[1] + 1]
    ]
end

def mine(map)
    m = map.first.length 
    n = map.length

    c = []
    map.each_with_index do |row, i |
        m.times do |j|
            if row[j] == '*'
                c.concat( adjacents [i,j] )
            end
        end
    end 
    c = c.find_all{|y,x| y >= 0 && y < n && x >= 0 && x < m}

    map.each_with_index do |row, i|
        m.times do |j|
            if row[j] != '*'
                row[j] = c.count([i,j]).to_s
            end
        end
    end
    map
end

#puts mine ["*...", "....", ".*..", "...."]
#puts mine ["**...", ".....", ".*..."]

input = STDIN.read.split(/[\r\n]/).drop(1)
puts mine input

2014/03/07 16:43

Kim Jaeju

#!/usr/bin/python

import os
import sys

def main():
    if len(sys.argv) is 1:
        print "set input file"

    else:
        f = open(sys.argv[1],'r')
        line = f.readline()
        a=int(line.split()[0])
        b=int(line.split()[1])
        mineLoc = f.read()
        #print(mineLoc)
        for i in range (0, a):
            for j in range (0, b):
                if mineLoc[i*(b+1)+j] == ".":
                    num = 0
                    if decFun(i-1,j-1,a,b):
                        if mineLoc[(i-1)*(b+1)+j-1] == "*":
                            num=num+1
                    if decFun(i-1,j,a,b):
                        if mineLoc[(i-1)*(b+1)+j] == "*":
                            num=num+1
                    if decFun(i-1,j+1,a,b):
                        if mineLoc[(i-1)*(b+1)+j+1] == "*":
                            num = num + 1
                    if decFun(i,j-1,a,b):
                        if mineLoc[i*(b+1)+j-1] == "*":
                            num = num + 1
                    if decFun(i,j+1,a,b):
                        if mineLoc[i*(b+1)+j+1] == "*":
                            num = num + 1
                    if decFun(i+1,j-1,a,b):
                        if mineLoc[(i+1)*(b+1)+j-1] == "*":
                            num = num + 1
                    if decFun(i+1,j,a,b):
                        if mineLoc[(i+1)*(b+1)+j] == "*":
                            num = num + 1
                    if decFun(i+1,j+1,a,b):
                        if mineLoc[(i+1)*(b+1)+j+1] == "*":
                            num = num + 1
                    print(num),
                else:
                    print(mineLoc[i*(b+1)+j]),
            print ''
    return None

def decFun(x,y,a,b):
    if x < 0:
        return 0
    if x >= a:
        return 0
    if y < 0:
        return 0
    if y >= b:
        return 0
    return 1


if __name__ == '__main__':
    main()
    sys.exit(0)

2014/03/08 02:59

sungho

의도가 맞는지 모르겠네요^^; 파이썬입니다.

import random

def printMatrix(_list):
    for row in _list:
        print ("   ".join(row))

def randomBomb():
    bomb=['*','.']
    return random.choice(bomb)

m = int(input("컬럼개수를 입력하세요.[100이하]:")) 
n = int(input("열에 개수를 입력하세요.[0이상]:"))

n_matrix = []

for ndx in range(0,n):
    n_matrix.append(["*"] * m)


for ndx in range(0,n):
    for mdx in range(0,m):
            n_matrix[ndx][mdx]=randomBomb()

for ndx in range(0,n):
    for mdx in range(0,m):
            if n_matrix[ndx][mdx] != "*":
                bombCount = 0
                for x in range(-1,2):
                    for y in range(-1,2):
                        xindex = ndx + x
                        yindex = mdx + y
                        if xindex > -1 and yindex > -1 and xindex < m  and yindex < n:
                            if "*" == n_matrix[ndx + x][mdx + y]:
                                bombCount = bombCount + 1

                n_matrix[ndx][mdx]=str(bombCount)

printMatrix(n_matrix)

2014/03/10 15:29

무명소졸

clojure

(defn neighbour
  "
  # (neighbour 0 0)
  # ;=> ([0 1] [1 0] [1 1])
  "

  [x y]
  (for [x' [(dec x) x (inc x)]
        y' [(dec y) y (inc y)]
        :when (and (not= [x' y'] [x y])
                   (>= x' 0) (>= y' 0))]
    [x' y']))


(defn bomb-solve [w h field]
  (let [bomb \*]
    (for [i (range w)]
      (for [j (range h)]

        (if (= bomb (get-in field [i j]))
          bomb

          (->> (neighbour i j)
               (map #(get-in field %))
               (filter #{bomb})
               count))))))


(let [[w h] [4 4]
      field [[\* \. \. \.]
             [\. \. \. \.]
             [\. \* \. \.]
             [\. \. \. \.]]]
  (bomb-solve w h field))

;=> ((\* 1 0 0) (2 2 1 0) (1 \* 1 0) (1 1 1 0))

2014/03/23 08:28

김 은평

import java.util.Scanner;

public class FindBomb {
    public static void main(String args[]){
        StringBuffer sb=new StringBuffer();
        Scanner in=new Scanner(System.in);
        int N=in.nextInt(), M=in.nextInt(), i, j, ii, jj, n;
        char[][] boardC=new char[N][M]; //N,M 입력받아서 char boardC[N][M]을 만듦
        String[] boardS=new String[N];
        for(i=0;i<N;i++){ //입력
           boardS[i]=in.next(); //boardS[N]으로 String으로 입력받음
           for(j=0;j<M;j++) boardC[i][j]=boardS[i].charAt(j); //한글자씩 boardC[N][M]에 집어넣음
        }
        for(i=0;i<N;i++){
            for(j=0;j<N;j++){
                System.out.println(i+" : "+j);
                if(boardC[i][j]=='*'){
                    sb.append("*");
                    continue;
                }else{
                    int cnt=0;                  
                    for(ii=i>0?i-1:0;ii<=(i+1>=N?(N-1):i+1);ii++){
                        for(jj=j>0?j-1:0;jj<=(j+1>=N?(N-1):j+1);jj++){
                            System.out.println(ii+" : "+jj);
                            if(boardC[ii][jj]=='*')cnt++;
                        }
                    }
                    sb.append(cnt);
                }
            }
            sb.append("\n");
        }
        System.out.println(sb.toString());
    }
}

Katherine님꺼의 입력부분 참고하여 만들었습니다.

2014/04/25 12:53

23king

[python2.7.3] random 함수를 이용하여 random한 숫자로 지뢰 갯수를 만들도록 구현해보았습니다. random하게 지뢰를 만들고, random.shffle로 역시 random하게 지뢰를 흩뜨려놓습니다. 지뢰를 찾는 방법은 앞에 다른분들과 비슷하게 loop를 돌면서 지뢰를 찾도록 하였습니다.

import random
import sys

inputMN = raw_input()
landminesMN = inputMN.split(' ')

M = int(landminesMN[0])
N = int(landminesMN[1])

if N <= 0 or M > 100 :
    sys.exit()

K = random.randrange(0,M*N) #spidermine count
landminesMap = [ ['.']*M for i in range(N) ]
showminesMap = [ ['*']*M for i in range(N) ]

def createLandMine(M,N,K) :
    landmineMark = M*N-K
    ttL = [i for i in range(landmineMark)]
    for i in range(K) :
        ttL.append(landmineMark)
    random.shuffle(ttL)     #random spread mine

    cnt = 0
    for i in range(N) :
        for j in range(M) :                        
            mark = '*' if ttL[cnt]==landmineMark else '.'
            print mark,
            landminesMap[i][j] = mark
            cnt += 1
        print ""

def showMap(M,N) :
    for i in range(N) :
        for j in range(M) :
            if landminesMap[i][j]=='.' :
                mineCnt = 0
                for a in range(i-1,i+2) :
                    for b in range(j-1,j+2) :
                        if a==i and b==j :
                            pass
                        elif a>=0 and a<N and b>=0 and b<M and landminesMap[a][b]=='*' :
                            mineCnt += 1
                showminesMap[i][j] = str(mineCnt)
            print showminesMap[i][j],
        print ""

createLandMine(M,N,K)
print "\n\nanswewr :"
showMap(M,N)

결과

4 4

. . . *

. . . *

. . . .

. * * *

answewr :

0 0 2 *

0 0 2 *

1 2 4 3

1 * * *

2014/06/11 16:43

suker

파이썬 입니다. * 주위에 8개 위치에 대해 각각 조건을 달아 1씩 더 하는 방식으로 풀어보았습니다.

def mine_finder(matrix):
    raw_num = len(matrix)
    col_num = len(matrix[0])
    for i in xrange (raw_num):
        for j in xrange (col_num):
            if matrix[i][j] == ".":
                matrix[i][j] = 0

    for i in xrange (raw_num):
        for j in xrange (col_num):
            if matrix[i][j] == "*":
                if i <= raw_num-2 and matrix[i+1][j] != "*":
                    matrix[i+1][j] += 1
                if j <= col_num-2 and matrix[i][j+1] != "*":
                    matrix[i][j+1] += 1
                if i <= raw_num-2 and j <= col_num-2 and matrix[i+1][j+1] != "*":
                    matrix[i+1][j+1] += 1
                if i >= 1 and matrix[i-1][j] != "*":
                    matrix[i-1][j] += 1
                if j >= 1 and matrix[i][j-1] != "*":
                    matrix[i][j-1] += 1
                if i >= 1 and j >= 1 and matrix[i-1][j-1] != "*":
                    matrix[i-1][j-1] += 1
                if i <= raw_num-2 and j >= 1 and matrix[i+1][j-1] != "*":
                    matrix[i+1][j-1] += 1
                if i >= 1 and j <= col_num-2 and matrix[i-1][j+1] != "*":
                    matrix[i-1][j+1] += 1

    return matrix                    


matrix = []
temp_matrix = raw_input().split("\n")
for item in temp_matrix:
    line = list(item)
    matrix.append(line)

result = mine_finder(matrix)

for item in result:
    print "".join(list(map(str, item)))

2014/11/02 15:25

돌구늬ㅋ~썬

파이썬 입니다. 어렵진 않았는데 코드가 만족스럽진 않네요.

# -*- coding: utf-8 -*- 
count = []

def func(s):
  lines = s.splitlines()
  m = len(lines)
  n = len(lines[0])

  for i in range(m):
    x = ''
    for j in range(n): x += '0' 
    count.append(list(x))

  for i in range(m): # 행
    for j in range(n): # 열
      if lines[i][j] == '*' : 
        count[i][j] = '*' 
        if i+1 <= m : count[i+1][j] = int(count[i+1][j]) + 1 
        if i-1 >= 0 : count[i-1][j] = int(count[i-1][j]) + 1 
        if j+1 <= n : count[i][j+1] = int(count[i][j+1]) + 1 
        if j-1 >= 0 : count[i][j-1] = int(count[i][j-1]) + 1 
        if i+1 <= m and j+1 <= n : count[i+1][j+1] = int(count[i+1][j+1]) + 1 
        if i-1 >= 0 and j+1 <= n : count[i-1][j+1] = int(count[i-1][j+1]) + 1
        if i+1 <= m and j-1 >= 0 : count[i+1][j+1] = int(count[i+1][j-1]) + 1 
        if i-1 >= 0 and j-1 >= 0 : count[i-1][j-1] = int(count[i-1][j-1]) + 1
  for i in range(len(count)):
    for j in range(len(count[0])):
      print count[i][j],
    print ''

func('*...\n....\n.*..\n....')

2015/01/10 20:24

Sang Brian

C#으로 작성했습니다. O(n^2)가 되지 않게 하려고 최대한 노력하였으나, 딱히 다른 방법이 생각나지 못해 이렇게 작성했습니다. 한 줄 읽는 즉시 이미 설정해놓은 mineAnswer double array에 값을 더했고, 지뢰가 위치한 곳에는 출력할 때 알아보려고 10을 더 더했습니다.

        public void GetMines(int row, string line, int[,] mines)
        {
            if (!line.Contains("*")) return;
            for (int j = 0; j < line.Length; j++)
            {
                if (line[j] == '*')
                {
                    if (row - 1 >= 0) // if current row - 1 exists
                    {
                        mines[row - 1, j]++;
                        if (j - 1 >= 0) mines[row - 1, j - 1]++;
                        if (j + 1 < line.Length) mines[row - 1, j + 1]++;
                    }
                    if (j - 1 >= 0) mines[row, j - 1]++; // current row
                    if (j + 1 < line.Length) mines[row, j + 1]++; 
                    if (row + 1 < mines.GetLength(0)) // if next row exists
                    {
                        mines[row + 1, j]++;
                        if (j - 1 >= 0) mines[row + 1, j - 1]++;
                        if (j + 1 < line.Length) mines[row + 1, j + 1]++;
                    }
                    mines[row, j] += 10; // if there is a mine, mark it as 10
                }
            }

2015/01/19 21:07

Straß Böhm Jäger

#include <stdio.h>

char arr[100][100] = {'\0',};
int result[100][100] = {0,};

int MINE = 1000;

int main()
{
    int n=0,m=0, x=1;
    int mineCnt=0;

    while(1)
    {
        int i=0,j=0;
        arr[0][0] = '\0';

        scanf("%d %d",&n,&m);
        if(n == 0 && m == 0 ) break;

        for(i=0;i<n;i++){
            scanf("%s",&arr[i]);
        }

        for(i=0;i<n;i++){
            for(j=0;j<m;j++){
                if(arr[i][j] == '*') result[i][j] = MINE;
                else{
                    if(i-1>=0 && j-1>=0 && arr[i-1][j-1] == '*')        mineCnt++;
                    if(i-1>=0 && arr[i-1][j] == '*')                    mineCnt++;
                    if(i-1>=0 && j+1<m && arr[i-1][j+1] == '*')     mineCnt++;
                    if(j+1<m && arr[i][j+1] == '*')                 mineCnt++;
                    if(i+1<n && j+1<m && arr[i+1][j+1] == '*')      mineCnt++;
                    if(i+1<n && arr[i+1][j] == '*')                 mineCnt++;
                    if(i+1<n && j-1>=0 && arr[i+1][j-1] == '*')     mineCnt++;

                    result[i][j] = mineCnt;
                    mineCnt = 0;
                }
            }
        }

        printf("Field #%d\n",x++);
        for(i=0;i<n;i++){
            for(j=0;j<m;j++){
                if(result[i][j] == MINE)    printf("*");
                else                        printf("%d",result[i][j]);
            }
            printf("\n");
        }
    }
    return 0;
}

2015/03/05 22:07

Park Kwan-Ung

    Sub Main()
        Dim input() As Integer = Array.ConvertAll(Split(Console.ReadLine, " "), Function(d As String) CInt(d))
        Dim size As New Size(input(0), input(1))

        Dim map(size.Height - 1)() As String

        For y As Integer = 0 To size.Height - 1
            map(y) = Array.ConvertAll(Console.ReadLine.ToArray, Function(c As Char) c.ToString)
        Next

        For y As Integer = 0 To size.Height - 1
            For x As Integer = 0 To size.Width - 1
                If map(y)(x) = "." Then
                    Dim c As Integer = 0

                    If x > 0 Then If map(y)(x - 1) = "*" Then c += 1
                    If x < size.Width - 1 Then If map(y)(x + 1) = "*" Then c += 1
                    If y > 0 Then If map(y - 1)(x) = "*" Then c += 1
                    If y < size.Height - 1 Then If map(y + 1)(x) = "*" Then c += 1

                    If x > 0 And y > 0 Then If map(y - 1)(x - 1) = "*" Then c += 1
                    If x < size.Width - 1 And y > 0 Then If map(y - 1)(x + 1) = "*" Then c += 1
                    If x < size.Width - 1 And y < size.Height - 1 Then If map(y + 1)(x + 1) = "*" Then c += 1
                    If x > 0 And y < size.Height - 1 Then If map(y + 1)(x - 1) = "*" Then c += 1

                    map(y)(x) = c
                End If
                Console.Write(map(y)(x))
            Next
            Console.WriteLine()
        Next

        Console.ReadLine()
    End Sub

2015/06/14 21:33

Steal

    static void exce34()// 지뢰찾기
    {

        String input = "";
        String[] stage;
        int read;
        char[][] output;
        FileInputStream fis = null;

        try
        {
            fis = new FileInputStream(input_url + "exce34.dat");
        } catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try
        {
            while ((read = fis.read()) > 0)
            {
                input += (char) read;
            }
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        stage = input.split("\n");
        output = new char[stage.length][stage[0].length()];

        for (int i = 0; i < stage.length; i++)
        {
            for (int j = 0; j < stage[i].length(); j++)
            {
                if (stage[i].charAt(j) == '.')
                {
                    int cnt = 0;

                    if (i > 0)
                    {
                        if (stage[i - 1].charAt(j) == '*')
                            cnt++;
                        if (j > 0 && stage[i - 1].charAt(j - 1) == '*')
                            cnt++;
                        if (j + 1 < stage[i].length() && stage[i - 1].charAt(j + 1) == '*')
                            cnt++;
                    }

                    if (i + 1 < stage.length)
                    {
                        if (stage[i + 1].charAt(j) == '*')
                            cnt++;
                        if (j > 0 && stage[i + 1].charAt(j - 1) == '*')
                            cnt++;
                        if (j + 1 < stage[i + 1].length() && stage[i + 1].charAt(j + 1) == '*')
                            cnt++;
                    }

                    if (j > 0 && stage[i].charAt(j - 1) == '*')
                        cnt++;

                    if (j + 1 < stage[i].length() && stage[i].charAt(j + 1) == '*')
                        cnt++;

                    output[i][j] = (char) (cnt + '0');
                } else if (stage[i].charAt(j) == '*')
                    output[i][j] = '*';
            }
        }

        for (int i = 0; i < output.length; i++)
        {
            for (int j = 0; j < output[i].length; j++)
                System.out.printf("%c", output[i][j]);

            System.out.println();
        }

    }

지뢰판 입력은 파일입력으로 받았습니다.

2015/08/27 14:00

조서현

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace Probleam
{
    class Program
    {
        static void Main(string[] args)
        {
            string read = Console.ReadLine();
            int width = int.Parse(read.Split(' ')[0]);
            int height = int.Parse(read.Split(' ')[1]);
            string[,] map = new string[width, height];
            for(int y = 0;y<height;y++)
            {
                string text = Console.ReadLine();
                for(int x = 0;x<width;x++)
                {
                    map[x, y] = text[x].ToString();
                }
            }
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    if(map[x,y] == "*")
                    {
                        if(x < width-1)
                        {
                            if (map[x + 1, y] != "*")
                            map[x + 1, y] = map[x + 1, y] == "." ? "1" : (int.Parse(map[x + 1, y]) + 1).ToString();
                        }
                        if(x>0)
                        {
                            if(map[x-1,y] != "*")
                            map[x -1, y] = map[x - 1, y] == "." ? "1" : (int.Parse(map[x - 1, y]) + 1).ToString();
                        }
                        if(y<height-1)
                        {
                            if (map[x , y+1] != "*")
                                map[x, y + 1] = map[x, y + 1] == "." ? "1" : (int.Parse(map[x, y + 1]) + 1).ToString();
                        }
                        if (y > 0)
                        {
                            if (map[x, y - 1] != "*")
                                map[x, y - 1] = map[x, y - 1] == "." ? "1" : (int.Parse(map[x, y - 1]) + 1).ToString();
                        }
                        if (x < width - 1 && y < height - 1)
                        {
                            if (map[x + 1, y+1] != "*")
                                map[x + 1, y+1] = map[x + 1, y+1] == "." ? "1" : (int.Parse(map[x + 1, y+1]) + 1).ToString();
                        }
                        if (x < width - 1 && y > 0)
                        {
                            if (map[x + 1, y - 1] != "*")
                                map[x + 1, y - 1] = map[x + 1, y - 1] == "." ? "1" : (int.Parse(map[x + 1, y - 1]) + 1).ToString();
                        }
                        if (x >0 && y < height - 1)
                        {
                            if (map[x - 1, y + 1] != "*")
                                map[x - 1, y + 1] = map[x - 1, y + 1] == "." ? "1" : (int.Parse(map[x - 1, y + 1]) + 1).ToString();
                        }
                        if (x > 0&& y > 0)
                        {
                            if (map[x - 1, y - 1] != "*")
                                map[x - 1, y - 1] = map[x - 1, y - 1] == "." ? "1" : (int.Parse(map[x - 1, y - 1]) + 1).ToString();
                        }
                    }
                }
            }
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    Console.Write(map[x, y] == "." ? "0":map[x,y]);
                }
                Console.WriteLine();
            }
        }
    }
}

2015/10/12 01:44

정우진

제가 썻지만, 난해하네요 -_-;

from itertools import product
m,n = map(eval,raw_input().split())
matrix =[]
for i in range(n):
    matrix.append(list(raw_input()))
m=len(matrix)
n=len(matrix[0])
for i in range(m):
    for j in range(n):
        if matrix[i][j] =='*' : continue
        matrix[i][j] = str([  matrix[y][x] for y,x in
            [  (i+di,j+dj) for di,dj in product([-1,0,1],repeat=2)  ]
            if x in range(n) and y in range(m)  ].count('*'))
print '\n'.join([''.join(l) for l in matrix])

2016/01/19 16:40

상파

생각보다 짧게되진 않네요. LiveScript입니다. 게임판은 1차원 배열로 다룹니다. 특정 인덱스 주변의 인덱스들을 구하는 함수가 1차원 배열을 쓴 덕에 좀 길어진 듯 하네요.

sample = """
    *...
    ....
    .*..
    ...."""
sample-size = [4 4]

main = (sample, sample-size) !->
    [w, h] = sample-size
    data = sample - /[\s\n]/g |> (.split '')

    offset-of = (i) ->
        [a, b] = [i % w, Math.floor i / w]
        s = [[a + x, b + y] for x from -1 to 1 
             for y from -1 to 1 when x*2+y != 0]
            .filter (e) -> 0 <= e[0] < w and 0 <= e[1] < h
            .map (e) -> e[0]+e[1]*w

    count-mine = (i) ->
        offset-of i .filter -> data[it] == '*'
            .length
        |> (data.it =)

    data.map (e, i) ->
        if e != '*' then data[i] = count-mine i .to-string!
        else data[i] = '*'

    [[data[x+y*w] for x til w].join '' for y til h] * '\n' 
    |> console.log

main sample, sample-size

2016/03/24 10:37

룰루랄라

Ruby

풀이 1. hassh. key = 2d array index.

def search_mines
  grid = gets.split[1].to_i.times.
           flat_map {|r| gets.chop.chars.map.with_index {|v,c|[[r,c],v]}}.to_h
  cnt = ->x,y { [*x-1..x+1].product([*y-1..y+1]).map(&grid).count "*" }
  puts grid.map {|xy,v| v == "." ? cnt[*xy] : "*"}.join.scan(/.{4}/)
end   

풀이 2. matrix 풀이 추가

require 'matrix'

def search_mines
  grid = Matrix[*gets.split[1].to_i.times.map {gets.chop.chars}]
  cnt = ->x,y { grid.minor(x-(x<=>0)..x+1, y-(y<=>0)..y+1).count "*" }
  grid.each_with_index {|c,x,y| grid.send(:[]=, x, y, cnt[x,y]) if c == "." }
  puts grid.to_a.map &:join
end

Test

$stdin = StringIO.new("4 4\n*...\n....\n.*..\n....\n")
expect{ search_mines }.to output("*100\n2210\n1*10\n1110\n").to_stdout

Output

search_mines
4 4
*...
....
.*..
....
*100
2210
1*10
1110

2016/03/24 16:05

rk

파이썬3.4입니다. m, n을 서로 반대로 봤네요~ 어쨌든 결과는 나오네요^^

DIR = {
    (-1, -1), (-1, 0), (-1, 1),
    (0, -1), (0, 1),
    (1, -1), (1, 0), (1, 1), }

m, n = input().split()
m = int(m)
n = int(n)

map_li=[]
for i in range(n):
    map_li.append(input())

map_ = {}
for i in range(n):
    for j in range(m):
        if map_li[i][j] is '.':
            map_[i, j] = 0
        else:
            map_[i, j] = map_li[i][j]

for key, val in map_.items():
    if val is '*':
        for d in DIR:
            dx, dy = d[0], d[1]
            x, y = key[0], key[1]
            newx, newy = dx + x, dy + y
            if newx < 0 or newx > n - 1 or newy < 0 or newy > m - 1:
                pass
            else:
                if map_[newx, newy] is '*':
                    pass
                else:
                    map_[newx, newy] += 1

for i in range(n):
    for j in range(m):
        print(map_[i, j], end = '')
    print()

2016/03/27 08:48

디디

sample = ['''*...
....
.*..
....''','''**...
.....
.*...''']

class mp():
    def __init__(self, blueprint):
        self.m = self.initialize(blueprint)
        self.bake()
    def initialize(self, blueprint):
        result = []
        for i, y in enumerate(blueprint):
            result.append([])
            for x in y:
                result[i].append(('*' if x == '*' else 0))
        return result
    def add(self, y, x):
        for j in range(-1,2):
            for i in range(-1,2):
                if (j == i and i == 0):
                    continue
                if 0<=y+j<=len(self.m)-1 and 0<=x+i<=len(self.m[y])-1:
                    if self.m[y+j][x+i] != '*':
                        self.m[y+j][x+i] += 1    
    def bake(self):
        for j, y in enumerate(self.m):
            for i, x in enumerate(y):
                if x == '*':
                    self.add(j, i)

if __name__ == '__main__':
    for x in range(len(sample)):
        sample[x] = sample[x].split('\n')
        for j in mp(sample[x]).m:
            for i in j:
                print(i, end = ' ')
            print()
        print()

객체지향 만세! 파이썬 3.5.1

2016/04/14 01:33

Flair Sizz

파이썬3.5.1

y,x = map(int,input().split())
mine = []
for i in range(y):
    mine.append((' '.join(input())).split())
for i in range(len(mine)): #여기부터
    mine[i].insert(0,'.')
    mine[i].append('.')
mine.insert(0, ['.'] * (x + 2))
mine.append(['.'] * (x + 2)) #여기까지 *에서 IndexError 방지위한 방화벽(?) 추가
for xx in range(1,y+1):
    for yy in range(1,x+1):
        if mine[xx][yy] != '*':
            s = [mine[xx+i][yy+j] for i in range(-1,2) for j in range(-1,2)] #*
            mine[xx][yy] = str(s.count('*'))
for i in range(len(mine)):
    mine[i] = ''.join(mine[i][1:-1])
print('\n'.join(mine[1:-1]))

2016/04/17 16:26

차우정

Python 3.4.4

matrix = []
bomb = []

def find_bomb(x, y):
    for j in range(x + 1, x - 2, -1):
        for i in range(y + 1, y - 2, -1):
            try:
                if i >= 0 and j >= 0:
                    matrix[j][i] = str(int(matrix[j][i]) + 1)
            except IndexError:
                pass
            except ValueError:
                pass

# input data
m, n = map(int, input().split())
for x in range(0, n):
    matrix.append(list(input()))

for y in range(0, n):
    for x in range(0, m):
        if matrix[y][x] == '*':
            bomb.append([y, x])
        else:
            matrix[y][x] = '0'

for x in bomb:
    find_bomb(int(x[0]), int(x[1]))

# print result
for x in range(n):
    print(''.join(matrix[x]))

2016/05/12 18:39

SanghoSeo

package javaCoding;

import java.util.ArrayList; import java.util.Random; import java.util.Scanner;

//자바로 만들었습니다.

public class Coding011 {

public static void main(String[] args) {

  Scanner input=new Scanner(System.in);
  System.out.println("지뢰 크기 입력");
  int input1=Integer.parseInt(input.nextLine());

  System.out.println("지뢰 크기 입력");
  int input2=Integer.parseInt(input.nextLine());

  System.out.println("지뢰 수 입력");
  int input3=Integer.parseInt(input.nextLine());

  String[][] ar=new String[input1][input2];

  for (int i = 0; i < input1; i++) {

     for (int j = 0; j < input2; j++) {

        ar[i][j]="-";
     }

  }


  Random ran=new Random();
  Random rnd = new Random();



  int[] lottoNumbers = new int[input3];          
  for (int i = 0; i < lottoNumbers.length; i++) {

     lottoNumbers[i] = rnd.nextInt(input2-1);

     // 중복된 값이 있으면 다시 랜덤값 구하기 위해 확인해서 index 값 줄여준다.    
     for (int j = 0; j < i; j++) {          
        if (lottoNumbers[i] == lottoNumbers[j]) {           
           i--;                
           break;             
           }           
        } 
  }


  for (int i = 0; i < lottoNumbers.length; i++) {
     int star=ran.nextInt(input1-1);
     ar[star][lottoNumbers[i]]="*";
  }


  int count=0;

  for (int i = 0; i < input1; i++) {

     for (int j = 0; j < input2; j++) {

        if(!(ar[i][j].equals("*"))){


        try{   
        if(ar[i-1][j-1].equals("*")){
           count++;
        }
        }
        catch(Exception e){

        }
        try{
        if(ar[i-1][j].equals("*")){
           count++;
        }

        }
        catch(Exception e){

        }
        try{
        if(ar[i][j-1].equals("*")){
           count++;
        }

        }
        catch(Exception e){

        }
        try{
        if(ar[i+1][j+1].equals("*")){
           count++;
        }

        }
        catch(Exception e){

        }
        try{
        if(ar[i+1][j].equals("*")){
           count++;
        }

        }
        catch(Exception e){

        }
        try{
        if(ar[i][j+1].equals("*")){
           count++;
        }

        }
        catch(Exception e){

        }
        try{
        if(ar[i-1][j+1].equals("*")){
           count++;
        }

        }
        catch(Exception e){

        }

        try{
        if(ar[i+1][j-1].equals("*")){
           count++;
        }
        }   
        catch(Exception e){

        }

        ar[i][j]=count+"";
        count=0;

        }

     }

  }


  for (int i = 0; i < input1; i++) {

     for (int j = 0; j < input2; j++) {

        System.out.print(ar[i][j]);
     }
     System.out.println("");
  }

}

}

2016/06/28 09:04

정 성훈

Swift3로 2차원 배열을 만들어서 풀어보았습니다. 코드가 너무 지저분하네요;;

//  Write some awesome Swift code, or import libraries like "Foundation",
//  "Dispatch", or "Glibc"

struct Array2D<T> : CustomStringConvertible {
  typealias Element = T
  private var array: [T?]
  var row: Int
  var col: Int
  init(row:Int, col:Int) {
    self.row = row
    self.col = col
    array = Array(repeating: nil, count: row * col)
  }

  subscript(row:Int, col:Int)  -> T? {
    get {
        guard case (0..<self.row) = row, case (0..<self.col) = col else {
          return nil
        }
        return array[col + row * self.row]
    }
    set {
        guard case (0..<self.row) = row, case (0..<self.col) = col else {
          return 
        }
        return array[col + row * self.row] = newValue
    }
  }

  var description: String {
    let title =  "2D Array with \(row) x \(col):\n"
    let body = (0..<row).map{ 
          array[$0*row..<(($0+1)*row)].map{ if $0 == nil { return "*" }; return "\($0!)" }
          .joined(separator:" ") 
        }.joined(separator:"\n")
    return title + body
  }

}

extension Array2D {
    func solution() -> Array2D<Int> {
        let offsets = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
        var result = Array2D<Int>(row:self.row, col:self.col)
        for i in 0..<self.row {
            for j in 0..<self.col {
                if let k = self[i, j] as? String, k != "*" {
                    var q = 0
                    for case let (x, y) in offsets where self[i+x, j+y] != nil {
                        if let x = self[i+x, j+y] as? String, x == "*" {q += 1}
                    }
                    result[i, j] = q
                }
            }
        }
        return result
    }
}

let qmap = ["*.*.", 
            "*...", 
            ".*..", 
            "...*"]

let mn = "4 4" 
do{
  let _cs = mn.characters.split(separator:" ").map{ Int(String($0))! }
  let (m, n) = (_cs[0], _cs[1])
  var ar = Array2D<String>(row:m, col:n)
  for i in 0..<m {
    let k = qmap[i].characters.map{ String($0) }
    for j in 0..<n {
      ar[i, j] = k[j]
    }
  }
  print(ar.solution())
}

2016/08/29 18:01

룰루랄라

JavaScript

지뢰마다 주변에 1씩 더하는 걸로 구현했습니다.

String.prototype.stripMargin = function() {
  return this.split("\n").map(line => line.replace(/^ *\|/g, "")).join("\n");
}

let rows = 4;
let cols = 4;
let input = `*...
            |....
            |.*..
            |...*`.stripMargin().split("\n").map(line => line.split(""))

let result = new Array(rows).fill(0).map(() => new Array(cols).fill(0))
for (let r = 0; r < rows; r++) {
  for (let c = 0; c < cols; c++) {
    if (input[r][c] == "*") {
      for (let i = Math.max(0, r - 1); i <= Math.min(rows - 1, r + 1); i++) {
        for (let j = Math.max(0, c - 1); j <= Math.min(cols - 1, c + 1); j++) {
          result[i][j] ++;
        }
      }
    }
  }
}

for (let r = 0; r < rows; r++) {
  for (let c = 0; c < cols; c++) {
    if (input[r][c] == "*") {
      result[r][c] = "*";
    }
  }
}

console.log(result.map(line => line.join("")).join("\n"))

2016/12/05 15:17

Han Jooyung

m,n = input().split(' ')
metrics = [list('.'*(int(n)+2))] +\
          [list('.'+input()+'.') for x in range(int(m))] +\
          [list('.'*(int(n)+2))]
print(metrics)
for x in range(1,int(m)+1):
    for y in range(1,int(n)+1):
        if metrics[x][y] != '*':
            metrics[x][y] = (metrics[x-1][y-1:y+2]+metrics[x+1][y-1:y+2]+metrics[x][y-1:y+2]).count('*')

#### 2016.12.27 D-422 ####

2016/12/27 22:28

GunBang

C언어 입니다.

  1. 기본적으로 배열의 원소를 기준으로 해서 행 열 각각에 -1 + 1 한 범위의 8개을 검사합니다.

  2. 비교하는 범위가 생성한 배열 행열의 크기를 벗어나면 플레그 값을 0으로 세팅해서 해당 경우의 수는 카운팅 하지 않게 했습니다.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    // heap 메모리에 행렬을 생성하고 지뢰를 세팅 과정

    int row, col, i, j;
    int cnt, x_under_flag, y_under_flag, x_over_flag, y_over_flag;
    char** pA;

    scanf("%d %d", &row, &col);

    pA = malloc(  sizeof(char*) * row );

    for( i = 0; i < row; i++ )
    {
        pA[i] = malloc( sizeof( char ) * col );
    }

    for( i = 0; i < row; i++ )
    {
        scanf("%s", pA[i]);
    }


    // 행렬에서 지뢰와 주변에 지뢰의 갯수를 표시

    for( i = 0; i < row; i++ )
    {
        for( j = 0; j < col; j++ )
        {

            // 만약 지뢰인 경우는 * 로 출력

            if( pA[i][j] == '*' )
            {
                printf("%c", '*');
            }

            // 지뢰가 아닌경우 배열의 요소에서 주변 8개를 전부 검사

            else
            {
                cnt = 0;

                x_over_flag  = 1;
                y_over_flag  = 1;
                x_under_flag = 1;
                y_under_flag = 1;

                // 배열의 범위를 벗어나는지 플레그를 통해 표현, 0 이면 범위를 벗어남.

                if( i - 1 < 0)
                {
                    x_under_flag = 0;
                }

                if(i + 1 >= row)
                {
                    x_over_flag = 0;
                }

                if( j - 1 < 0)
                {
                    y_under_flag = 0;
                }

                if( j + 1 >= col)
                {
                    y_over_flag = 0;
                }


                // 배열의 요소에서 주변 8개를 검사, 단 배열의 범위를 벗어난 경우는 제외

                if( x_under_flag && (pA[i-1][j] == '*') )
                    cnt++;

                if( x_over_flag && (pA[i+1][j] == '*'))
                    cnt++;

                if( y_under_flag && (pA[i][j-1] == '*') )
                    cnt++;

                if( y_over_flag && (pA[i][j+1] == '*'))
                    cnt++;

                if( x_over_flag && y_under_flag && (pA[i+1][j-1] == '*'))
                    cnt++;

                if( x_under_flag && y_over_flag && (pA[i-1][j+1] == '*'))
                    cnt++;

                if( x_under_flag && y_under_flag && (pA[i-1][j-1] == '*'))
                    cnt++;

                if( x_over_flag && y_over_flag && (pA[i+1][j+1] == '*'))
                    cnt++;  


                // 범위를 벗어난 경우를 제외하고 지뢰의 갯수를 출력

                printf("%d", cnt);
            }
        }

        // 열 검사를 끝내고 다음 줄 검사.

        printf("\n");
    }


    // heap 메모리 정리

    for( i = 0; i < row; i++ )
    {
        free(pA[i]);
    }

    free(pA);

    return 0;
}

2017/02/08 21:33

f-reversing

def mine(data):
    n=data[0][0]
    m=data[0][1]
    data=[["."]]+data[1:n+1][:]+[["."]]
    for i in range(m+1):
        data[0]+=["."]
        data[n+1]+=["."]
    for j in range(n):
        data[j+1]=["."]+data[j+1]+["."]
    for i in range(1,n+1):
        for j in range(1,m+1):
            if data[i][j]!="*":
                data2=data[i-1:i+2]
                data[i][j]=0
                for k in range(3):
                    data[i][j]+=data2[k][j-1:j+2].count("*")
    data=data[1:n+1]
    for i in range(n):
        data[i]=data[i][1:m+1]
    return data
mine([[4,4],["*",".",".","."],[".",".",".","."],[".","*",".","."],[".",".",".","."]])

2017/02/14 03:24

김구경

import java.util.Scanner;

import static java.lang.System.in;

public class LandMineSearch {

    public static void main(String[] args) {
        Scanner sc = new Scanner(in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        String[][] a = new String[n][m];

        for (int i = 0; i < n; i++) {
            String[] line = sc.next().split("");
            for (int j = 0; j < m; j++) {
                a[i][j] = "0";
                if (line[j].equals("*")) a[i][j] = "*";
            }
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (a[i][j].equals("*")) {

                    if (j - 1 >= 0) {
                        String b = a[i][j - 1];
                        a[i][j - 1] = String.valueOf(Integer.valueOf(b) + 1);
                    }

                    if (i - 1 >= 0 && j - 1 >= 0) {
                        String b = a[i - 1][j - 1];
                        a[i - 1][j - 1] = String.valueOf(Integer.valueOf(b) + 1);
                    }

                    if (i - 1 >= 0) {
                        String b = a[i - 1][j];
                        a[i - 1][j] = String.valueOf(Integer.valueOf(b) + 1);
                    }

                    if (i - 1 >= 0 && j + 1 < 4) {
                        String b = a[i - 1][j + 1];
                        a[i - 1][j + 1] = String.valueOf(Integer.valueOf(b) + 1);
                    }

                    if (j + 1 < 4) {
                        String b = a[i][j + 1];
                        a[i][j + 1] = String.valueOf(Integer.valueOf(b) + 1);
                    }

                    if (i + 1 < n && j + 1 < m) {
                        String b = a[i + 1][j + 1];
                        a[i + 1][j + 1] = String.valueOf(Integer.valueOf(b) + 1);
                    }

                    if (i + 1 < n) {
                        String b = a[i + 1][j];
                        a[i + 1][j] = String.valueOf(Integer.valueOf(b) + 1);
                    }

                    if (i + 1 < n && j - 1 >= 0) {
                        String b = a[i + 1][j - 1];
                        a[i + 1][j - 1] = String.valueOf(Integer.valueOf(b) + 1);
                    }
                }
            }
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.print(a[i][j]);
            }
            System.out.println();
        }
    }
}

2017/03/16 16:53

genius.choi

// 지뢰찾기 - C
#include <stdio.h>
#include <conio.h>

int main(void)
{
    int m, n; // 가로 세로 설정값
    int i, j; // for문 친구들
    char board[100][100]; // 지뢰판
    char select;
    // 변수를 활용한 배열 선언이 되지 않아 일단 최대 범위를 선언.
    printf("판의 행,열을 입력하세요. 행,열은 각각 1~100 범위 내에 있어야 합니다.\n");
    do
    {
        scanf("%d %d", &m, &n);
    } while (m > 100 || m < 1 || n > 100 || n < 1);
    for (i = m; i < 100; i++)
        for (j = n; j < 100; j++)
            board[i][j] = '_'; // '_'로 그 칸이 빈 것이라는 것을 표시한다.
    printf("지뢰로 지정할 칸은 *, 그러지 않을 칸은 .을 입력해주세요.\n");
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            while (1)
            {
                select = _getche();
                if (select == '*') // 둘 중 하나라면 지뢰 위치 지정하고 탈출.
                {
                    board[i][j] = 9; // 9는 지뢰라는 신호(최대 숫자는 8이니).
                    break;
                }
                else if (select == '.')
                {
                    board[i][j] = 0;
                    break;
                }
                else
                    printf("\b");
            }
        }
        printf("\n");
    }
    for (i = 0; i < m; i++) // 지뢰 숫자 표시 중
    {
        for (j = 0; j < n; j++)
        {
            if (board[i][j] != 9)
            {
                if (i != 0)
                {
                    if (board[i - 1][j] == 9)
                        board[i][j]++;
                    if (j != 0)
                        if (board[i - 1][j - 1] == 9)
                            board[i][j]++;
                    if (j != n - 1)
                        if (board[i - 1][j + 1] == 9)
                            board[i][j]++;
                }
                if (i != m - 1)
                {
                    if (board[i + 1][j] == 9)
                        board[i][j]++;
                    if (j != 0)
                        if (board[i + 1][j - 1] == 9)
                            board[i][j]++;
                    if (j != n - 1)
                        if (board[i + 1][j + 1] == 9)
                            board[i][j]++;
                }
                if (j != 0)
                    if (board[i][j - 1] == 9)
                        board[i][j]++;
                if (j != n - 1)
                    if (board[i][j + 1] == 9)
                        board[i][j]++;
            }
        }
    }
    for (i = 0; i < m; i++)// 결과 출력
    {
        for (j = 0; j < n; j++)
            if (board[i][j] == 9)
                printf("*");
            else
                printf("%d", board[i][j]);
        printf("\n");
    }
}

2017/06/05 23:19

Jeong Hoon Lee

python 3.5, 조현우님 답을 참조하여 scipy.signal.convolve2d 이용한 코드. 매우 깔끔해짐.

import numpy as np
from scipy import signal

# Put mine
m,n = map(int, input("Enter m*n: ").split())
mine = np.random.randint(2, size=(m,n))

# Fine mine
kernel = np.ones((3, 3))
result = signal.convolve2d(mine, kernel, 'same')

#print Mine & Result
hid, out = '', ''
for i in range(m):
    for j in range(n):
        if mine[i][j] == 1:
            hid += '*'
            out += '*'
        else:
            hid += '.'
            out += str(int(result[i][j]))
    hid += '\n'
    out += '\n'

print("%s\n%s" % (hid,out))

옛날코드, for 와 if 만 이용해서...너저분....

import numpy as np


m,n = map(int, input("Enter m*n: ").split())
a = np.random.randint(2, size=(m,n))
mine = []

for x in a:
    #row = ''
    row = []
    for y in x:
        if y: y = '*'
        else: y = '.'
        #row += y
        row.append(y)
    #print(row)
    print(''.join(row))
    mine.append(row)


look = ''
for i in range(m):
    for j in range(n):
        if mine[i][j] != '*':
            if i == 0:
                if j == 0:
                    look = mine[i][j+1] + mine[i+1][j+1] + mine[i+1][j]
                    mine[i][j] = str(look.count('*'))
                elif j == n-1:
                    look = mine[i][j-1] + mine[i+1][j-1] + mine[i+1][j]
                    mine[i][j] = str(look.count('*'))
                else:
                    look = mine[i][j-1] + mine[i+1][j-1] + mine[i+1][j] + mine[i][j+1] + mine[i+1][j+1]
                    mine[i][j] = str(look.count('*'))
            elif i == m-1:
                if j == 0:
                    look = mine[i][j+1] + mine[i-1][j+1] + mine[i-1][j]
                    mine[i][j] = str(look.count('*'))
                elif j == n-1:
                    look = mine[i][j-1] + mine[i-1][j-1] + mine[i-1][j]
                    mine[i][j] = str(look.count('*'))
                else:
                    look = mine[i][j-1] + mine[i-1][j-1] + mine[i-1][j] + mine[i][j+1] + mine[i-1][j+1]
                    mine[i][j] = str(look.count('*'))
            else:
                if j == 0:
                    look = mine[i-1][j] + mine[i+1][j] + mine[i][j+1] + mine[i-1][j+1] + mine[i+1][j+1]
                    mine[i][j] = str(look.count('*'))
                elif j == n-1:
                    look = mine[i-1][j] + mine[i+1][j] + mine[i][j-1] + mine[i-1][j-1] + mine[i+1][j-1]
                    mine[i][j] = str(look.count('*'))
                else:
                    look = mine[i-1][j] + mine[i+1][j] + mine[i][j-1] + mine[i-1][j-1] + mine[i+1][j-1] + mine[i][j+1] + mine[i-1][j+1] + mine[i+1][j+1]
                    mine[i][j] = str(look.count('*'))

print("Mines are found:")
for c in mine:
    print(''.join(c))

2017/06/06 03:59

예강효빠

javascript(ES6)

var getMimeMap = function(input) {
    var mime = input.split("\n").map(v => v.trim().split(""));
    var [M, N] = [mime && mime.length || 0, mime && mime[0] && mime[0].length || 0];
    var map = Array.from(Array(M), () => Array.from(Array(N), () => 0));

    var checkmime = function(arr, row, col) {
        arr[row][col] = "*";
    };

    var accumulate = function(arr, row, col) {
        if (row >= 0 && row < M && col >= 0 && col < N && mime[row][col] !== "*") {
            arr[row][col]++;
        }
    };

    mime.map(function(line, row) {
        line.map(function(cell, col) {
            if (cell === "*") {
                accumulate(map, row - 1, col - 1);
                accumulate(map, row - 1, col    );
                accumulate(map, row - 1, col + 1);
                accumulate(map, row    , col - 1);
                checkmime (map, row    , col    );
                accumulate(map, row    , col + 1);
                accumulate(map, row + 1, col - 1);
                accumulate(map, row + 1, col    );
                accumulate(map, row + 1, col + 1);
            }
            return cell;
        })
        return line;
    });

    return map;
};

var printMimeMap = function(map) {
    console.log(map.map(v => v.join("")).join("\n"));
};

var input1 = 
`*...
....
.*..
....`;

printMimeMap(getMimeMap(input1));

> *100
> 2210
> 1*10
> 1110

var input2 =
`*...
....
.*..
....`;

printMimeMap(getMimeMap(input2));

*100
2210
1*10
1110

var input3 =
`**...
.....
.*...`;

printMimeMap(getMimeMap(input3));

> **100
> 33200
> 1*100

2017/06/17 01:05

funnystyle

C#: 그냥 C 스타일로...

class MineSweeper
{
    static char[,] arr;
    static int N, M;

    public static int countMines(int x, int y)
    {
        int[] dx = new int[8] { -1, -1, -1, 0, 1, 1, 1, 0 };
        int[] dy = new int[8] { -1, 0, 1, 1, 1, 0, -1, -1 };
        int cnt = 0;

        for (int dir = 0; dir < 8; dir++)
        {
            int xx = x + dx[dir];
            int yy = y + dy[dir];
            if (xx >= 0 && xx < N &&
                yy >= 0 && yy < M &&
                arr[xx, yy] == '*')
                cnt++;
        }
        return cnt;
    }

    public static void sweep()
    {        
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < M; j++)
            {
                if (arr[i,j] == '*')
                {
                    Write('*');
                } else
                {
                    Write(countMines(i, j));
                }                
            }
            WriteLine();
        }
        WriteLine();
    }

    static void Main(string[] args)
    {        
        string[] rawData = new string[] {
            "4 4\n*...\n....\n.*..\n....",
            "3 5\n**...\n.....\n.*..."
        };

        foreach (var data in rawData)
        {
            string[] tmp = data.Split();
            N = int.Parse(tmp[0]);
            M = int.Parse(tmp[1]);
            arr = new char[N,M];
            for (int i = 0; i < N; i++)
            {
                for (int j = 0; j < M; j++)
                {
                    arr[i,j] = tmp[i + 2][j];
                }
            }
            sweep();
        }
    }
}

2017/07/23 20:17

Noname

Python

from itertools import product

data = '4 4\n*...\n....\n.*..\n....'
data = data.split()
N, M, arr = int(data[0]), int(data[1]), [list(line) for line in data[2:]]

for i in range(N):
    for j in range(M):
        if arr[i][j] == '*':
            c = '*'
        else:
            c = sum([0 <= x < N and 0 <= y < M and arr[x][y] == '*' \
                for (x, y) in product([i-1, i, i+1], [j-1, j, j+1])])

        print(c, end = ' ')
    print()

2017/07/23 20:35

Noname

파이썬3 가독성 포기하고 7줄에 넣어봤습니다

M, N = ( int(input('M : ')), int(input('N : ')))

bomb = ['.' for a in range(M) ]

for n in range(N):
    bomb.extend(list('.' + input('')))

res = [str([ bomb[n-(M+2)], bomb[n-(M+1)], bomb[n-(M)], bomb[n-1], bomb[n+1], bomb[n+(M+2)], bomb[n+(M+1)], bomb[n+(M)] ].count('*')) if a == '.' else bomb[n] for a, n in (zip(bomb,[a for a in range(0 , (len(bomb)//2))] + [a for a in range(-(len(bomb)//2), 0)]) if len(bomb)%2 == 0 else zip(bomb,[a for a in range(0 , (len(bomb)//2))] + [a for a in range(-(len(bomb)//2 + 1), 0)]))]

for n in range(1,N+1):
    print( ''.join(res[n * (M+1) : (n + 1) * (M+1) - 1]))

가독성을 약간 높인

M, N = ( int(input('M : ')), int(input('N : ')))

res = []

bomb = ['.' for a in range(M) ]

for n in range(N):
    bomb.extend(list('.' + input('')))

list = [a for a in range(0 , (len(bomb)//2))]
list1 = list + [a for a in range(-(len(bomb)//2), 0)]
list2 = list + [a for a in range(-(len(bomb)//2 +1), 0)]

for a,n in zip(bomb,(list1 if len(bomb) % 2 == 0 else list2) ):
    if a == '.':
        res.extend(str([ bomb[n-(M+2)], bomb[n-(M+1)], bomb[n-(M)], bomb[n-1], bomb[n+1], bomb[n+(M+2)], bomb[n+(M+1)], bomb[n+(M)] ].count('*')))
    else:
        res.extend(bomb[n])

for n in range(1,N+1):
     print( ''.join(res[n * (M+1) : (n + 1) * (M+1) - 1]))

문자열을 받은 후 위와 왼쪽 줄에 .을 추가해서 계산하는 방식입니다

예를 들어

..

..

..* 가 입력되면

....

...

...

...* 으로 변환하여 계산합니다

2017/07/24 01:48

이재희

row, col = map(int, input().split())


matrix = []
for i in range(row):
    matrix.append(list(input()))


for i in range(row):
    for j in range(col):
        if matrix[i][j] == "*":
            continue
        else:
            matrix[i][j] = 0

for i in range(row):
    for j in range(col):
        if matrix[i][j] == 0:
            for x in range(i-1,i+2):

                if x<0 or x>=row:
                    continue

                for y in range(j-1, j+2):
                    if y<0 or y>=col:
                        continue

                    elif matrix[x][y] == "*":
                        matrix[i][j] = matrix[i][j]+1


for i in matrix:
    for j in i:
        print(j, end="")
    print()

2017/08/04 02:43

JY C

public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int x = scan.nextInt();
        int y = scan.nextInt();

        String[][] arr = new String[x][y];

        scan.nextLine();

        //입력받은 n*n 배열에 지뢰 투척
        for(int i=0;i<x;i++){   
            String line = scan.nextLine();
            String[] qq= line.split("");
            for(int j=0;j<y;j++){
                arr[i][j]=qq[j];
            }
        }

        //지뢰 숫자세서 출력
        for(int i=0;i<arr.length;i++){
            for(int j=0;j<arr[i].length;j++){
                if(arr[i][j].equals("*")){

                }else{
                    int cnt=0;
                    //첫행의 맨앞
                    if(i==0 && j==0){
                        String temp=arr[i][j+1]+arr[i+1][j];
                        String[] tempArr =temp.split("");
                        for(String t: tempArr){
                            if(t.equals("*")){
                                cnt++;
                            }
                        }
                    }
                    //첫행의 맨 앞과 맨 뒤 빼고
                    else if(i==0 && j!=0 && j!=arr[i].length-1){
                        String temp =arr[i][j-1]+arr[i][j+1]+arr[i+1][j];
                        String[] tempArr =temp.split("");
                        for(String t: tempArr){
                            if(t.equals("*")){
                                cnt++;
                            }
                        }
                    }
                    //첫행의 맨 끝
                    else if(i==0 && j==arr[i].length-1){
                        String temp = arr[i][j-1]+arr[i+1][j];
                        String[] tempArr =temp.split("");
                        for(String t: tempArr){
                            if(t.equals("*")){
                                cnt++;
                            }
                        }
                    }
                    //맨왼쪽 중간
                    else if(j==0 && i!=0 && i!=arr.length-1){
                        String temp = arr[i-1][j]+arr[i][j+1]+arr[i+1][j]+arr[i-1][j+1]+arr[i+1][j+1];
                        String[] tempArr =temp.split("");
                        for(String t: tempArr){
                            if(t.equals("*")){
                                cnt++;
                            }
                        }
                    }
                    //맨왼쪽 맽아래
                    else if(j==0 && i==arr.length-1){
                        String temp = arr[i-1][j]+arr[i][j+1]+arr[i-1][j+1];
                        String[] tempArr =temp.split("");
                        for(String t: tempArr){
                            if(t.equals("*")){
                                cnt++;
                            }
                        }
                    }
                    //맨아래 중간
                    else if(i==arr.length-1 && j!=0 && j!= arr.length-1){
                        String temp =arr[i][j-1]+arr[i-1][j]+arr[i][j+1]+arr[i-1][j-1]+arr[i-1][j+1];
                        String[] tempArr =temp.split("");
                        for(String t: tempArr){
                            if(t.equals("*")){
                                cnt++;
                            }
                        }
                    }
                    //맨오른쪽맨끝
                    else if(i==arr.length-1 && j==arr.length-1){
                        String temp = arr[i][j-1]+arr[i-1][j];
                        String[] tempArr =temp.split("");
                        for(String t: tempArr){
                            if(t.equals("*")){
                                cnt++;
                            }
                        }
                    }
                    else if(j==arr.length-1 && i!=0 && i!=arr.length-1){
                        String temp = arr[i-1][j]+arr[i][j-1]+arr[i+1][j];
                        String[] tempArr =temp.split("");
                        for(String t: tempArr){
                            if(t.equals("*")){
                                cnt++;
                            }
                        }
                    }else{
                        String temp=arr[i-1][j-1]+arr[i-1][j]+arr[i-1][j+1]+arr[i][j-1]+arr[i][j+1]+arr[i+1][j-1]+arr[i+1][j]+arr[i+1][j+1];
                        String[] tempArr =temp.split("");
                        for(String t: tempArr){
                            if(t.equals("*")){
                                cnt++;
                            }
                        }
                    }
                    //중간지점


                    arr[i][j]=String.valueOf(cnt);


                }

            }
        }
        //지뢰 투척 잘 됐나 확인
        for(String[] tmp : arr){
            for(String qwe:tmp){
                System.out.print(qwe);
            }
            System.out.println();
        }

    }

2017/09/26 17:33

김문수

package codingdojang;

import java.util.Scanner;

public class ex34 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);
    int M = sc.nextInt();
    int N = sc.nextInt(); sc.nextLine();

    char arr[][] = new char[M][N];
    int c[][] = new int[M][N];

    for(int i=0; i<M; i++) {
        String temp = sc.nextLine();
        for(int j=0; j<N; j++) {
            arr[i][j] = temp.charAt(j);
        }
    }


    for(int i=0; i<M; i++) {
        for(int j=0; j<N; j++) {
            if(arr[i][j] == '*') {
                if(i>0)
                c[i-1][j]++;

                if(i<M-1)
                c[i+1][j]++;

                if(j>0)
                c[i][j-1]++;

                if(j<N-1)
                c[i][j+1]++;

                if(i>0 && j>0)
                c[i-1][j-1]++;

                if(i>0 && j<N-1)
                c[i-1][j+1]++;

                if(i<M-1 && j>0)
                c[i+1][j-1]++;

                if(i<M-1 && j<N-1)
                c[i+1][j+1]++;

            }
        }
    }

    for(int i=0; i<M; i++) {
        for(int j=0; j<N; j++) {
            if(arr[i][j] != '*') {
                System.out.print(c[i][j]);
            }
            else {
                System.out.print(arr[i][j]);
            }
        }
        System.out.println();
    }


}

}

2017/10/06 15:59

이병호

dim = str(input())
dim = dim.split()
r_row = int(dim[0])
c_col = int(dim[1])
mine = []
for i in range(r_row):
    mine.append(list(input()))


def add_count(i, j):
    if i < 0 or i >= r_row: return
    if j < 0 or j >= c_col: return
    if mine[i][j] == '*': return

    if mine[i][j] == '.':
        mine[i][j] = 1
    else:
        mine[i][j] += 1

def get_around(row, col):
    for i in range(row-1, row+2):
        for j in range(col-1, col+2):
            add_count(i, j)

def get_mine_num():
    for row in range(len(mine)):
        for col in range(len(mine[row])):
            if mine[row][col] == '*':
                get_around(row, col)
            elif mine[row][col] == '.':
                mine[row][col] = 0

get_mine_num()

for i in mine:
    for j in i:
        print(j, end='')
    print()

2017/11/28 23:36

Sung Kim

col, row=map(int, input().split())
matrix=[]
for i in range(row):
    matrix.append(list(input()))

for i in range(len(matrix)):
    for j in range(len(matrix[i])):
        if matrix[i][j]=='*':
            continue
        else:
            matrix[i][j]=0
            for y in range(i-1,i+2):
                for x in y:
                    matrix[i][j]+1

여기까지 했는데 모르겠어요ㅜㅜㅜㅜㅜㅜㅜ고수님들 도와주세요ㅜㅜㅜㅜㅜ

2017/12/14 13:56

HYUN JUN KIM

파이썬 3.6

# 아이디어> 지뢰밭 요소의 값을 리스트 형태로 생성하여 문자열로 변환한 뒤, 지뢰밭 크기 조건에 따라 각 요소의 주변값을 확인하여 '*'요소의 값을 카운팅함

import random   

def minesearch(m,n,x):
    mines = []
    strmines = ''
    minecount = 0
    minecountlist = []
    indexlist =[]
    for i in range(x): mines.append('*')
    for i in range(m*n-x): mines.append('.')
    random.shuffle(mines)
# 입력 받은 지뢰수 만큼 먼저 '*'을 생성하고 남은수만큼 '.'을 생성하여, 각 요소의 위치를 임의의 위치로 재배열 
    strmines = ''.join(mines)
# 지뢰 위치 출력
    for i in range(m):
        for i in range(0,len(mines),n):
            print(' '.join(mines[:n]))
            del mines[:n]
    for i in enumerate(strmines):
        indexlist.append(i)
    print("\n"" >>> 각 위치의 인근지뢰수 정보입니다.","\n")
    for i in indexlist:
       if i[1] == '*':
           minecountlist.append(str(i[1]))
       else:
# 해당 요소의 주변 값들을 순차적으로 확인하여 '*'이 있는 경우 누적카운팅
# 첫행, 중간행, 마지막행, 각 행의 첫열, 중간열, 마지막열을 구분하여 각 요소별로 확인
           if i[0] == 0:
                for h in range(i[0]+1,i[0]+n+2):
                    if i[0]+1 < h < i[0]: pass
                    elif indexlist[h][1] == '*':
                       minecount += 1
            elif 0 < i[0] < n-1:
                for h in range(i[0]-1,i[0]+n+2):
                    if i[0]+1 < h < i[0]+n-1:pass
                    elif indexlist[h][1] == '*':
                        minecount += 1
            elif i[0] != len(strmines)-n and i[0]%n == 0:
                for h in range(i[0]-n,i[0]+n+2):
                    if i[0]-n+1 < h < i[0] or i[0]+1< h < i[0]+n or h > len(strmines)-1: pass
                    elif indexlist[h][1] == '*':
                        minecount += 1
            elif i[0] != len(strmines)-1 and i[0]%n == n-1:
                for h in range(i[0]-n-1,i[0]+n+1):
                    if i[0]-n < h < i[0]-1 or i[0] < h < i[0]+n-1 or h < 0: pass
                    elif indexlist[h][1] == '*':
                        minecount += 1
            elif n < i[0] < len(strmines)-n:
                for h in range(i[0]-n-1,i[0]+n+2):
                    if i[0]-n+1 < h < i[0]-1 or i[0]+1 < h < i[0]+n-1: pass
                    elif indexlist[h][1] == '*':
                        minecount += 1
            elif i[0] == len(strmines)-n:
                for h in range(i[0]-n,i[0]+2):
                    if i[0]-n+1 < h < i[0]: pass 
                    elif indexlist[h][1] == '*':
                        minecount += 1
            elif len(strmines)-n < i[0] <len(strmines)-1:
                for h in range(i[0]-n-1,i[0]+2):
                    if i[0]-n+1 < h < i[0]-1: pass
                    elif indexlist[h][1] == '*':
                        minecount += 1
            elif i[0] == len(strmines)-1:
                for h in range(i[0]-n-1,i[0]):
                    if i[0]-n < h < i[0]-1: pass
                    elif indexlist[h][1] == '*':
                        minecount +=1        
            minecountlist.append(str(minecount))
            minecount = 0
# 결과 출력
    for i in range(m):
        for i in range(0,len(minecountlist),n):
            print(' '.join(minecountlist[:n]))
            del minecountlist[:n]

def main():
    m = int(input(" ▶ M(ROW(행))값을 입력하세요(0 < M <=100) : "))
    if m < 0  or m > 100:
        print("\n"" ※ 범위안의 값을 입력해주세요. ","\n")
        return
    n = int(input(" ▶ N(COLIMN(열))값을 입력하세요 (0 < N <=100): "))
    if n < 0  or n > 100:
        print("\n"" ※ 범위안의 값을 입력해주세요. ","\n")
        return
    x = random.randint(2, m*n//2)
    print( "\n"" ※ %d X %d (지뢰수 random 생성)"%(m,n),"\n")
    minesearch(m,n,x)

if __name__ == "__main__":
    main()

*결과값

 ▶ M(ROW(행))값을 입력하세요(0 < M <=100) : 10
 ▶ N(COLIMN(열))값을 입력하세요 (0 < N <=100): 10

 ※ 10 X 10 (지뢰수 random 생성) 

. . . . . . . . . .
. * . . . * . * . .
. . . . . * * . . .
* . . . . * . . . .
. * . * . . * * . .
. . . . . * . . . *
. . . . . . . * . .
. * . . * * . . . .
* . . . . * . . * .
. . . . . . . . . .

 >>> 각 위치의 인근지뢰수 정보입니다. 

1 1 1 0 1 1 2 1 1 0
1 * 1 0 2 * 4 * 1 0
2 2 1 0 3 * * 2 1 0
* 2 2 1 3 * 5 3 1 0
2 * 2 * 3 3 * * 2 1
1 1 2 1 2 * 4 3 3 *
1 1 1 1 3 3 3 * 2 1
2 * 1 1 * * 3 2 2 1
* 2 1 1 3 * 2 1 * 1
1 1 0 0 1 1 1 1 1 1

2018/01/05 13:07

justbegin

Store comonad를 사용하여 만들어보았습니다.

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}
import Control.Comonad.Store
import Data.Ix
import Data.Char
import qualified Data.Map as Map
import Data.List.Split

type MatrixC a = Store Point a
type Point = (Int, Int)

vecAdd (a,b) (c,d) = (a+c, b+d)

neighbor8 :: Point -> [Point]
neighbor8 p
  = [ vecAdd p (dx, dy)
    | dx <- [1,0,-1]
    , dy <- [1,0,-1]
    , (dx, dy) /= (0, 0)
    ]

rule :: MatrixC Bool -> Char
rule mat
  | extract mat == True
    = '*'
  | otherwise
    = intToDigit
    . length
    . filter id
    . experiment neighbor8
    $ mat

minesweeper :: MatrixC Bool -> MatrixC Char
minesweeper = extend rule

-- I/O

parse :: Int -> Int -> String -> MatrixC Bool
parse x y s = store (\i -> Map.findWithDefault False i m) undefined
  where
    m = Map.fromList
      $ zip (range ((1,1),(x,y)))
      $ fmap (=='*')
      $ filter (not . isSpace) s

render :: Int -> Int -> MatrixC Char -> String
render x y
  = unlines . chunksOf y
  . experiment (const $ range ((1,1),(x,y)))

main :: IO ()
main = do
  [x, y] :: [Int]
    <-  fmap read . words
    <$> getLine

  getContents >>= putStr
    . render x y . minesweeper . parse x y

2018/01/05 14:54

sodii

# 파이썬

sample = """4 4
*...
....
.*..
...."""


def mine_finder(input1):
    input1 = input1.split("\n")
    map1 = []
    for t in input1[1:]:
        raw = [0] + [0 if x == "." else "*" for x in t] + [0]
        map1.append(raw)
    map1 = [[0 for _ in range(len(map1[0]))]] + map1 + [[0 for _ in range(len(map1[0]))]]
    # 여기까지 입력값을 *과 0을 요소로 하는 2중 리스트로 만들고 열과 행을 위아래좌우로 하나씩 추가합니다. 
    for m, u in enumerate(map1):
        for n, v in enumerate(u):
            if v == "*":
                map1[m-1][n-1] += 1
                map1[m-1][n] += 1
                map1[m-1][n+1] += 1
                map1[m][n-1] += 1
                map1[m][n+1] += 1
                map1[m+1][n-1] += 1
                map1[m+1][n] += 1
                map1[m+1][n+1] += 1
    # 여기까지 * 주위값들을 1씩 추가합니다.
    for q in map1[1:-1]:
        for r in q[1:-1]: print(str(r), end='')
        print('')


mine_finder(sample)




2018/02/06 17:01

olclocr

def landmine(l):
    m = list()
    for i in range(len(l)):
        m.append([])
        for j in range(len(l[0])):
            m[i].append(0)
    for i in range(len(l)):
        for j in range(len(l[i])):
            if l[i][j] == '*':
                m[i][j] = '*'
            if l[i][j] == '*':
                if l[i-1][j-1] == '.':
                    m[i-1][j-1] += 1
                if l[i-1][j] == '.':
                    m[i-1][j] += 1
                if l[i-1][j+1] == '.':
                    m[i-1][j+1] += 1
                if l[i][j-1] == '.':
                    m[i][j-1] += 1
                if l[i][j+1] == '.':
                    m[i][j+1] += 1
                if l[i+1][j-1] == '.':
                    m[i+1][j-1] += 1
                if l[i+1][j] == '.':
                    m[i+1][j] += 1
                if l[i+1][j+1] == '.':
                    m[i+1][j+1] += 1
    for i in range(len(m)):
        m[i] = m[i][1:len(m[i])-1]
    m = m[1:len(m)-1]
    return m

a = list()
while True:
    n = input()
    if n == "":
        break
    else:
        a.append(n)
a[0] = list(map(int, a[0].split(' ')))
c = a[0][0]
d = a[0][1]
b = list()
b.append('.'*(d+2))
for i in range(1,len(a)):
    b.append('.'+a[i]+'.')
b.append('.'*(d+2))
for i in landmine(b):
    print(i)

2018/02/08 12:51

김동하

size_num=input("마지막 숫자 입력후 바로\\n누르세요\n")
mnlist=[]
for s in size_num.split(" "):
    mnlist.append(int(s))
M=mnlist[0]
N=mnlist[1]

location_list=[]
for g in range(M):
    location_list.append(input())

bomb_location_set=set()
m_count=0
for b in location_list:
    n_count=0
    for a in b:
        if a=="*":
            bomb_location_set.add((m_count,n_count))
            n_count+=1
        else:
            n_count+=1
            continue
    m_count+=1

array=[[0]*N for line in range(M)]
M=M-1
N=N-1

for location in bomb_location_set:
    m,n=location
    if m!=0 and m!=M and n!=N and n!=0:
        array[m][n - 1] += 1
        array[m][n + 1] += 1
        array[m + 1][n] += 1
        array[m - 1][n] += 1
        array[m-1][n-1]+=1
        array[m-1][n+1]+=1
        array[m+1][n-1]+=1
        array[m+1][n+1]+=1

    elif m == 0 and n != 0 and n != N:
        array[m][n - 1] += 1
        array[m][n + 1] += 1
        array[m + 1][n] += 1
        array[m+1][n-1]+=1
        array[m+1][n+1]+=1

    elif m == M and n != 0 and n != N:
        array[m][n - 1] += 1
        array[m][n + 1] += 1
        array[m - 1][n] += 1
        array[m - 1][n - 1] += 1
        array[m - 1][n + 1] += 1

    elif m != 0 and m != M and n == 0:
        array[m][n + 1] += 1
        array[m - 1][n] += 1
        array[m-1][n+1]+=1
        array[m + 1][n] += 1
        array[m+1][n+1]+=1

    elif m != 0 and m != M and n == N:
        array[m][n - 1] += 1
        array[m - 1][n] += 1
        array[m-1][n-1]+=1
        array[m + 1][n] += 1
        array[m+1][n-1]+=1

    elif m==0 and n==0:
        array[m+1][n]+=1
        array[m][n+1]+=1
        array[m+1][n+1]+=1

    elif m==0 and n==N:
        array[m+1][n]+=1
        array[m+1][n-1]+=1
        array[m][n-1]+=1

    elif m==M and n==0:
        array[m][n+1]+=1
        array[m-1][n]+=1
        array[m-1][n+1]+=1

    elif m==M and n==N:
        array[m][n-1]+=1
        array[m-1][n]+=1
        array[m-1][n-1]+=1

for location in bomb_location_set:
    m,n=location
    array[m][n]='*'




for line in array:
    line_str=''
    for element in line:
        line_str+=str(element)
    print(line_str)









먼저 각 부분 숫자 구한다음 마지막에 폭탄 위치 표시하게 했습니다

2018/02/18 07:46

D B

자바입니당... 코드가 넘 지저분하네요 ㅜ

package CodingDojang;

import java.util.*;

public class MineSweeper {

    private static String[][] sweep(char[][] _inputs) {
        String[][] outputs = new String[_inputs.length][_inputs[0].length];

        for(int i = 0; i < _inputs.length; i++) {
            for(int j = 0; j < _inputs[i].length; j++) {
                if(_inputs[i][j] == '.') {
                    int mineCount = 0;
                    int[] indexIList = {i-1, i, i+1};
                    int[] indexJList = {j-1, j, j+1};

                    for(int _i = 0; _i < indexIList.length; _i++) {
                        for(int _j = 0; _j < indexJList.length; _j++) {
                            try {
                                if(_inputs[indexIList[_i]][indexJList[_j]] == '*') {
                                    mineCount++;
                                }
                            } catch(Exception e) {}
                        }
                    }

                    outputs[i][j] = "" + mineCount;
                } else {
                    outputs[i][j] = "" + _inputs[i][j];
                }
            }
        }
        return outputs;
    }

    public static void main(String args[]) {
        Scanner scn = new Scanner(System.in);
        String[] inputStrs;
        char[][] inputs;
        String[][] outputs;
        int[] rowCol = new int[2];

        for(int i = 0; i < rowCol.length; i++) {
            rowCol[i] = scn.nextInt();
        }

        inputStrs = new String[rowCol[0]];
        inputs = new char[rowCol[0]][rowCol[1]];
        outputs = new String[rowCol[0]][rowCol[1]];

        for(int i = 0; i < inputStrs.length; i++) {
            inputStrs[i] = scn.next();
        }

        for(int i = 0; i < inputs.length; i++) {
            for(int j = 0; j < inputs[i].length; j++) {
                inputs[i][j] = inputStrs[i].charAt(j);
            }
        }

        outputs = sweep(inputs);

        for(int i = 0; i < outputs.length; i++) {
            for(int j = 0; j < outputs[i].length; j++) {
                System.out.printf("%s", outputs[i][j]);
            }
            System.out.printf("\n");
        }

        scn.close();
    }   
}

2018/03/01 15:37

sangw0804

파이썬으로 작성했습니다. 격자위치에서 상하좌우의 인덱스를 모두 확인해 지뢰의 개수를 카운트하는 방식으로 작성했습니다.

m=int(input(''))
n=int(input(''))

bomb=[ [input('') for p in range(n)] for q in range(m)]

for line in bomb:
    print(''.join(line))
for i in range(m):
    for j in range(n):
        count=0
        if bomb[i][j]!='*':
            if i-1>=0:
                if bomb[i-1][j]=='*':
                    count+=1
                if j-1>=0 and bomb[i-1][j-1]=='*':
                    count+=1
                if j+1<n and bomb[i-1][j+1]=='*':
                    count+=1
            if i+1<m:
                if bomb[i+1][j]=='*':
                    count+=1
                if j-1>=0 and bomb[i+1][j-1]=='*':
                    count+=1
                if j+1<n and bomb[i+1][j+1]=='*':
                    count+=1
            if j-1>=0 and bomb[i][j-1]=='*':
                count+=1
            if j+1<n and bomb[i][j+1]=='*':
                count+=1
            bomb[i][j]=str(count)
for line in bomb:
    print(''.join(line))

2018/03/18 17:36

박종범

row,column = map(int,input("matrix:").split(" "))                              
matrix = []
solution_matrix = [[] for n in range(0,row)]
for n in range(0,row):
    matrix.append(input())                                     #테스트할 행렬 입력, 행 만큼 반복

for i in range(0,row):
    for j in range(0,column):
        i_i, i_f, j_i, j_f = (i-1, i+1, j-1, j+1)              #i,j 주변 값의 범위 설정
        if i == 0:                                             #경계부분 범위 조정
            i_i = i
        if j == 0:
            j_i = j
        if i  == row-1:
            i_f = i
        if j == column-1:
            j_f = j

        if matrix[i][j] == '.':
            a_matrix = []                                       #a_matrix는 i,j 주변의 값
            for x in range(i_i,i_f+1):
                for y in range(j_i,j_f+1):
                    a_matrix.append(matrix[x][y])
            solution_matrix[i].insert(j,str(a_matrix.count('*')))

        else:
            solution_matrix[i].insert(j,'*')

for n in range(0,row):                                         #리스트를 문자열로 변환하기 위해 join사용
    print("".join(solution_matrix[n]))

2018/03/23 03:30

정익수

import java.util.Scanner;

public class Mine {

    public static String[][] execute(String[][] param){

        String[][] matrix = new String[param.length][param[0].length];

        for(int i=0; i< param.length; i++){
            for(int j=0; j<param[0].length; j++){
                if(param[i][j].equals("*")){ //지뢰인경우
                    matrix[i][j] = "*";
                }else{ //지뢰아니면
                    int count = 0;
                    if(i > 0 && j > 0 && param[i-1][j-1].equals("*")){ // 좌상
                        count++;
                    }
                    if(i > 0 && param[i-1][j].equals("*")){ // 상
                        count++;
                    }
                    if(i > 0 && j < param[0].length-1 && param[i-1][j+1].equals("*")){ // 우상
                        count++;
                    }
                    if(j < param[0].length-1 && param[i][j+1].equals("*")){ // 우
                        count++;
                    }
                    if(i < param.length-1 && j < param[0].length-1 && param[i+1][j+1].equals("*")){ // 우하
                        count++;
                    }
                    if(i < param.length-1 && param[i+1][j].equals("*")){ // 하
                        count++;
                    }
                    if(i < param.length-1 && j > 0 && param[i+1][j-1].equals("*")){ // 좌하
                        count++;
                    }
                    if(j > 0 && param[i][j-1].equals("*")){ // 좌
                        count++;
                    }
                    matrix[i][j] = Integer.toString(count);
                }
            }
        }
        return matrix;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);

        int row = sc.nextInt();
        int vertical = sc.nextInt();

        String[][] matrix = new String[row][vertical];

        for(int i=0; i< row; i++){
            String[] inputLine = sc.next().split("");
            for(int j = 0; j < vertical; j++){
                matrix[i][j] = inputLine[j];
            }
        }
        sc.close();

        matrix = execute(matrix);

        for(int i=0; i< row; i++){
            for(int j = 0; j < matrix[0].length; j++){
                System.out.print(matrix[i][j]);
            }
            System.out.println();
        }

    }

}

2018/03/27 17:05

김태훈

import numpy as np
M, N = input().split()
M = int(M)
N = int(N)
a_list = np.zeros((M+2, N+2), dtype = 'U')
b_list = np.zeros((M, N), dtype = 'U')
for i in range(M):
        line = input()
        for j in range(len(line)):
            a_list[i+1][j+1] = line[j]
for i in range(M):
    for j in range(N):
        count = 0
        if a_list[i+1][j+1] == '*':
            b_list[i][j] ='*'
            continue
        else:
            for q in range(3):
                for w in range(3):
                    if a_list[i+q][j+w] == "*":
                        count += 1
                    else:
                        continue
            b_list[i][j] = str(count)
print(b_list)

2018/04/02 16:12

최성범

// 지뢰찾기
package main

import (
    "fmt"
    "strings"
)

// mat: 매트릭스의 크기, 입력텍스트, 위치별 지뢰 갯수를 인스턴스 변수로 가진 객체 생
type mat struct {
    xMax, yMax int
    val        [][]string // 지뢰 텍스트
    count      [][]string // 인근 지뢰 갯수
}

// newMat: constructor
func newMat(xMax, yMax int, val [][]string) *mat {
    matrix := make([][]string, yMax)
    count := make([][]string, yMax)
    for y := 0; y < yMax; y++ {
        matrix[y] = make([]string, xMax)
        count[y] = make([]string, xMax)
        for x := 0; x < xMax; x++ {
            matrix[y][x] = val[y][x]
        }
    }
    m := mat{}
    m.xMax, m.yMax = xMax, yMax
    m.val = matrix
    m.count = count
    for y := 0; y < m.yMax; y++ {
        for x := 0; x < m.xMax; x++ {
            m.setPos(x, y)
        }
    }
    return &m
}

// setPos: 인근 지뢰 갯수 저장
func (m *mat) setPos(posx, posy int) {
    count := 0
    for y := posy - 1; y <= posy+1; y++ {
        if y < 0 || y >= m.yMax {
            continue
        }
        for x := posx - 1; x <= posx+1; x++ {
            if x < 0 || x >= m.xMax {
                continue
            }
            if m.val[y][x] == "*" {
                count++
            }
        }
    }
    if m.val[posy][posx] == "*" {
        m.count[posy][posx] = "*"
    } else {
        m.count[posy][posx] = fmt.Sprint(count)
    }
}

// solveMatrix: 결과 출력
func (m mat) solveMatrix() {
    for y := 0; y < m.yMax; y++ {
        for x := 0; x < m.xMax; x++ {
            fmt.Print(m.count[y][x], " ")
        }
        fmt.Println()
    }
}

// parsing
func parsing(aString string) (xMax, yMax int, inpMat [][]string) {
    tmp := strings.Split(aString, "\n")
    fmt.Sscanln(tmp[0], &xMax, &yMax)
    inpMat = make([][]string, yMax)
    for yidx, yval := range tmp[1:] {
        inpMat[yidx] = make([]string, xMax)
        for xidx, xval := range strings.Split(yval, "") {
            inpMat[yidx][xidx] = xval
        }
    }
    return
}

func main() {
    // 입력 예
    inpString := `4 4
*...
....
.*..
....`

    myNew := newMat(parsing(inpString))
    myNew.solveMatrix()
}

/* 출력
* 1 0 0
2 2 1 0
1 * 1 0
1 1 1 0
*/

2018/04/09 21:50

mohenjo

def findjirue(m,n):
    mylist = []
    for i in range(1,m+1):
        line = input("{}번째줄을 입력하시오 : ".format(i))
        while len(line) != n  :
            line = input("{0}번째줄을 다시 입력하시오(n={1}) : ".format(i, n))
        mylist.append(line)
    print("your table :")
    print("\n".join(mylist))
    print("your table's math : ")
    newlist= []
    for line in mylist :
        for chr in line :
            if chr == "." : newlist.append(0)
            else : newlist.append(chr)
    for i in range(len(newlist)):
        if newlist[i] == "*" :
            if i >= n and i % n != 0 and newlist[i-(n+1)] != "*": newlist[i-(n+1)] += 1
            if i >= n and newlist[i-n] != "*" : newlist[i-n] += 1
            if i >= n and i % n != n-1 and newlist[i-(n-1)] != "*" : newlist[i-(n-1)] += 1
            if i < len(newlist) - n and i % n != 0 and newlist[i + (n - 1)] != "*": newlist[i + (n - 1)] += 1
            if i < len(newlist) - n  and newlist[i + n ] != "*": newlist[i + n ] += 1
            if i < len(newlist) - n and i % n != n-1 and newlist[i + (n + 1)] != "*": newlist[i + (n + 1)] += 1
            if i % n != 0 and newlist[i-1] != "*" : newlist[i-1] += 1
            if i % n != n-1 and newlist[i+1] != "*" : newlist[i+1] += 1
    newlist = list(map(str,newlist))
    for i in range(m):
        print("".join(newlist[n * i:n * (i+1)]))

2018/04/17 15:09

yijeong

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>

  <script>

var ex = [[".", "*", "*"],["*", ".", "*"]]



    function gen (a, b) {
      var list_1 = [];
      for (var i = 0; i < a; i++){
        var list_2 = []
        for (var j = 0; j < b; j++){
                    if(Math.round(Math.random()) == 1) {
            list_2[j] = "*";
          } else {
            list_2[j] = ".";
          }
                  };
        list_1[i] = list_2;
      }
      return list_1
    };



    function check (l,x,y) {
      var count = 0;
      for(var i = -1 ; i<2; i++) {
        if (x == 0 && i < 0 ) {
          i = 0;
        };
      console.log("upper",i,j,x+i,y+j);
        for (var j = -1; j<2; j++) {
          if ( y == 0 && j < 0) {
            j = 0;
          };
          console.log("down",i,j,x+i,y+j);
         if ( x+i > l.length - 1) {
           console.log("before break");
           break;
           console.log("after break");
           return count;
         } else {
            if(l[x+i][y+j] === "*" ){
              count += 1;
            console.log("count", count);
            };
        };

        };
      };
      return count; 
    };



function trans (l) {
  for (var i = 0; i < l.length; i++) {
    for (var j = 0; j < l[0].length; j++) {
      if ( l[i][j] != "*" ) {
        l[i][j] = check(l,i,j);
      };
    };
  };
  return l;
};


function board_set (a, b) {
  var t = gen (a,b);
  trans(t);
  return t;
};







  </script>
</body>
</html>

2018/04/20 10:22

Yungbin Kim

Python 3

def findbombnum(bombmap):
    result = [[] for l in range(len(bombmap))]
    for y, line_y in enumerate(bombmap):
        for x, line_x in enumerate(line_y):
            if line_x == '*':
                result[y].append(line_x)
            else:
                bombcount = 0
                a = list(range(1, 4))[::-1]
                for yfind in a:
                    for xfind in a:
                        try:
                            if bombmap[y-yfind+2][x-xfind+2] == '*' and y-yfind+2 != -1 and x-xfind+2 != -1:
                                bombcount += 1
                        except: pass
                result[y].append(bombcount)
    return result
bomb = []
for args in range(int(input().split()[0])):
    bomb.append([obj for obj in input()])
for printy in findbombnum(bomb):
    for printx in printy:
        print(printx, end='')
    print()

2차원리스트를 사용하여 단순히 자신 주위의 8개를 모두 검토하는 방법입니다

2018/04/22 13:42

myyh2357

Python

dx = [0, -1, -1, -1, 0, 1, 1, 1]
dy = [-1, -1, 0, 1, 1, 1, 0, -1]
def func(matrix, m, n):
    result = list()
    for i in range(m):
        tmp_result = ""
        for j in range(n):
            if matrix[i][j] == "*":
                tmp_result += "*"
            else:
                n_ans = 0
                for k in range(8):
                    x = i + dx[k]; y = j + dy[k];
                    if 0 <= x <= m-1 and 0 <= y <= n-1 and matrix[x][y] == "*":
                        n_ans += 1
                tmp_result += str(n_ans)
        result.append(tmp_result)
    return result


m, n = map(int, input().split(' '))
matrix = list()
for i in range(m):
    matrix.append(input())
print(*func(matrix, m, n), sep="\n")

2018/06/04 16:33

Taesoo Kim

# 입력 부분
M, N = map(int, input("두 숫자(MxN)를 입력하세요(띄어쓰기로 구분): ").split())
matrix = []
for m in range(M):
    matrix.append(list(input()))

# 처리 부분
list1 = [[-1,-1], [-1,0], [-1,1],[0,-1], [0,1], [1,-1], [1,0], [1,1]] # 팔방 조사를 위한 8개의 리스트
for m in range(M):
    for n in range(N):
        if matrix[m][n] == "*":
            continue
        elif matrix[m][n] == ".":
            count = 0
            for x,y in list1:
                # 팔방조사중에 인덱스를 벗어나는 부분과 음수 조회를 방지
                try:
                    if (matrix[m+x][n+y] == "*") and m+x >= 0 and n+y >= 0:
                        count += 1
                except Exception as e:
                    pass
            matrix[m][n] = str(count)
        else:
            print("[err]데이터가 잘못 됐습니다.")

# 출력 부분
for m in matrix:
    print("".join(m))

2018/06/27 07:56

재즐보프

import sys
import numpy as np

def show_usage():
    print("m and n must be 0 < mn <= 100")
    sys.exit(0)

def get_input():
    mn_str = raw_input("type m x n : ")
    mn = mn_str.split(' ')

    for i in range(len(mn)):
        if int(mn[i]) <= 0 and int(mn[i]) > 100:
            show_usage()

    input_row = int(mn[0])
    input_col = int(mn[1])

    row_list = []

    for i in range(input_row):
        row = raw_input("{}th row : ".format(i+1))
        if len(row) != input_col:
            show_usage()
        row_list.append(row)
    print("{}".format(row_list))

    return ( (input_row,input_col), row_list )

def modify_number_around( array, r, c ):
    for row in range(-1,2):
        for col in range(-1,2):
            if row != 0 or col != 0:
                rr = r + row
                cc = c + col
                if rr >= 0 and rr < array.shape[0]:
                    if cc >= 0 and cc < array.shape[1]:
                        before = array[rr,cc]
                        array[rr,cc] += 1
                        after = array[rr,cc]

((input_row,input_col), row_l) = get_input()
array = np.zeros((input_row, input_col))

for i in range(len(row_l)):
    for j in range(len(row_l[i])):
        if row_l[i][j] == '*':
            array[i,j] = -9
            modify_number_around(array,i,j)

for i in range(array.shape[0]):
    for j in range(array.shape[1]):
        if array[i,j] < 0:
            print("*", end='')
        else:
            print(str(int(array[i,j])), end='')
    print("")

2018/07/03 21:11

구름과비

파이썬3

row = int(input("행 수를 입력하세요:"))
col = int(input("열 수를 입력하세요:"))
print("지뢰는 *로, 아닌 지역은 .을 입력하세요. 입력이 끝나면 end를 입력하세요.")
sentinel = 'end'
mines = list(iter(input, sentinel)) #sentinel: 보초병/감시병
print(mines)

for r in range(0, row):
    mines[r] = list(mines[r])
    for c in range(0, col):
        if mines[r][c] != '*':
            mines[r][c] = str([mines[i][j] for i in range(max(r-1,0), min(r+2,row)) for j in range(max(c-1,0), min(c+2, col))].count('*'))


for r in range(0, row):
    print("".join(mines[r]))

2018/07/07 07:14

WJ K

M,N = map(int,input().split())
board = []
for i in range(M):
    while 1:
        board.append(input())
        if len(board[-1]) != N:
            print("길이가 틀립니다. 재입력하세요.")
            del board[-1]
        else: break
# 출력
for i in range(M):
    for j in range(N):
        if board[i][j] != '*':
            tmpj = 0 if j-1 < 0 else j-1
            if i == 0: print(''.join(board[i][tmpj:j+2]+board[i+1][tmpj:j+2]).count('*'),end='')
            elif i == M-1: print(''.join(board[i][tmpj:j+2]+board[i-1][tmpj:j+2]).count('*'),end='')
            else: print(''.join(board[i][tmpj:j+2]+board[i-1][tmpj:j+2]+board[i+1][tmpj:j+2]).count('*'),end='')
        else: print('*',end='')
    print()
8 8     
...**..*
*.....*.
........
..*....*
........
....**..
*.......
.....***

111**22*
*11222*2
12110122
01*1001*
01122221
1101**10
*1013442
11001***

2018/07/12 20:35

Creator

// 
package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();
        mine(m,n);
    }

    public static void mine(int m, int n)
    {
        String[][] arr = set(m + 2, n + 2);//arr1
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
                System.out.print(search(m, n, arr)[i][j]);
            System.out.println();
        }
    }

    public static String[][] set(int m, int n) // 지뢰 설정
    {
        Scanner sc = new Scanner(System.in);
        String[][] arr1 = new String[m][n];
        for (int i = 0; i < m; i++) // "."으로 초기화
            for (int j = 0; j < n; j++)
                arr1[i][j] = ".";
        for (int i = 1; i < m - 1; i++) // 지뢰 설정
            for (int j = 1; j < n - 1; j++)
                arr1[i][j] = sc.next();
        sc.close();
        return arr1;
    }

    public static String[][] search(int m, int n, String[][] arr) // 주변지뢰 탐색
    {
        int count = 0;
        String[][] newArr = new String[m][n];
        for (int i = 1; i < m + 1; i++)
            for (int j = 1; j < n + 1; j++) {
                if (arr[i][j].equals("*"))
                    newArr[i - 1][j - 1] = arr[i][j];
                else
                    {
                    for (int a = i - 1; a <= i + 1; a++)
                        for (int b = j - 1; b <= j + 1; b++)
                        {
                            if (a == i && b == j)
                                continue;
                            else if (arr[a][b].equals("*"))
                                count++;
                        }
                    newArr[i - 1][j - 1] = String.valueOf(count);
                    count = 0;
                    }
            }
        return newArr;
    }
}

2018/07/14 19:36

이동수

파이썬 3.7입니다. 아는 함수가 적어서 어렵게 만들었네요... list자료형으로 매트릭스 구현해 보았습니다.

#입력
a = ('''***.*.
....*.
*.**..''')
x = a.split('\n')

R = []
for i in range(len(x)):
    r = []
    for j in range(len(x[i])):
        if i == 0 and j == len(x[i]) - 1: # 상단 우측 모서리
            if x[i][j] == '*':
                r.append('*')
                continue
            c = 0
            if x[i][j - 1] == '*': c += 1
            if x[i + 1][j] == '*': c += 1
            if x[i + 1][j - 1] == '*': c += 1
            r.append(str(c))
        elif i == 0 and j != 0 and j != len(x[i]) - 1: # 상단 중양
            if x[i][j] == '*':
                r.append('*')
                continue
            c = 0
            if x[i][j - 1] == '*': c += 1
            if x[i][j + 1] == '*': c += 1
            if x[i + 1][j - 1] == '*': c += 1
            if x[i + 1][j] == '*': c += 1
            if x[i + 1][j + 1] == '*': c += 1
            r.append(str(c))
        elif i == 0 and j == 0: # 상단 좌측 모서리
            if x[i][j] == '*':
                r.append('*')
                continue
            c = 0
            if x[i][j + 1] == '*': c += 1
            if x[i + 1][j] == '*': c += 1
            if x[i + 1][j + 1] == '*': c += 1
            r.append(str(c))
        elif i == len(x) - 1 and j == 0: # 하단 좌측 모서리
            if x[i][j] == '*':
                r.append('*')
                continue
            c = 0
            if x[i][j + 1] == '*': c += 1
            if x[i - 1][j] == '*': c += 1
            if x[i - 1][j + 1] == '*': c += 1
            r.append(str(c))
        elif i == len(x) - 1 and j == len(x[i]) - 1: # 하단 우측 모서리
            if x[i][j] == '*':
                r.append('*')
                continue
            c = 0
            if x[i][j - 1] == '*': c += 1
            if x[i - 1][j] == '*': c += 1
            if x[i - 1][j - 1] == '*': c += 1
            r.append(str(c))
        elif i == len(x) - 1 and j != 0 and j != len(x[i]) - 1: # 하단 중앙
            if x[i][j] == '*':
                r.append('*')
                continue
            c = 0
            if x[i][j - 1] == '*': c += 1
            if x[i][j + 1] == '*': c += 1
            if x[i - 1][j - 1] == '*': c += 1
            if x[i - 1][j] == '*': c += 1
            if x[i - 1][j + 1] == '*': c += 1
            r.append(str(c))
        elif j == 0 and i != 0 and i != len(x)-1: # 좌측 중앙
            if x[i][j] == '*':
                r.append('*')
                continue
            c = 0
            if x[i][j + 1] == '*': c += 1
            if x[i - 1][j] == '*': c += 1
            if x[i - 1][j + 1] == '*': c += 1
            if x[i + 1][j] == '*': c += 1
            if x[i + 1][j + 1] == '*': c += 1
            r.append((c))
        elif j == len(x[i]) - 1  and i != 0 and i != len(x)-1: # 우측 중앙
            if x[i][j] == '*':
                r.append('*')
                continue
            c = 0
            if x[i][j - 1] == '*': c += 1
            if x[i - 1][j] == '*': c += 1
            if x[i - 1][j - 1] == '*': c += 1
            if x[i + 1][j] == '*': c += 1
            if x[i + 1][j - 1] == '*': c += 1
            r.append(str(c))
        else: # 중앙
            if x[i][j] == '*':
                r.append('*')
                continue
            c = 0
            if x[i][j - 1] == '*': c += 1
            if x[i][j + 1] == '*': c += 1
            if x[i - 1][j - 1] == '*': c += 1
            if x[i - 1][j] == '*': c += 1
            if x[i - 1][j + 1] == '*': c += 1
            if x[i + 1][j - 1] == '*': c += 1
            if x[i + 1][j] == '*': c += 1
            if x[i + 1][j + 1] == '*': c += 1
            r.append(str(c))
    R.append(r)

for i in range(len(R)):
    print(R[i])

2018/08/21 19:55

김건우

C#

using System;
using System.Linq;

namespace CD034
{
    class Program
    {
        static void Main(string[] args)
        {
            string[,] matrix = InputAndParser(out int scaleY, out int scaleX);
            Mine mine = new Mine(scaleY, scaleX, matrix);
            mine.DisplaySolution();
        }

        // input & parser
        static string[,] InputAndParser(out int scaleY, out int scaleX)
        {
            int[] scale = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();
            scaleY = scale[0]; scaleX = scale[1];
            string[] lines = new string[scaleY];
            for (int line = 0; line < scaleY; line++)
            {
                lines[line] = Console.ReadLine();
            }
            // matrix parser
            string[,] matrix = new string[scaleY, scaleX];
            for (int row = 0; row < scaleY; row++)
            {
                for (int col = 0; col < scaleX; col++)
                {
                    matrix[row, col] = lines[row][col].ToString();
                }
            }
            return matrix;
        }
    }

    class Mine
    {
        private int scaleX, scaleY;
        private string[,] matrix; // 문제 매트릭스
        private string[,] matrixSolution; // 해답 매트릭스

        // constructor
        public Mine(int scaleY, int scaleX, string[,] matrix)
        {
            this.scaleY = scaleY; this.scaleX = scaleX;
            this.matrix = matrix;
            matrixSolution = new string[scaleY, scaleX];
        }

        private void GetSolution() // 전체 셀에 대한 카운트 계산
        {
            for (int row = 0; row < scaleY; row++)
            {
                for (int col = 0; col < scaleX; col++)
                {
                    CellCount(row, col);
                }
            }
        }

        private void CellCount(int posY, int posX) // 한 셀에 대한 카운트
        {
            int count = 0;
            for (int y = posY - 1; y <= posY + 1; y++)
            {
                if (y < 0 || y >= scaleY) { continue; }
                for (int x = posX - 1; x <= posX + 1; x++)
                {
                    if (x < 0 || x >= scaleX) { continue; }
                    if (matrix[y, x] == "*") { count++; }
                }
            }
            if (matrix[posY, posX] == "*") { matrixSolution[posY, posX] = "*"; }
            else { matrixSolution[posY, posX] = count.ToString(); }
        }

        public void DisplaySolution()
        {
            GetSolution();
            for (int row = 0; row < scaleY; row++)
            {
                for (int col = 0; col < scaleX; col++)
                {
                    Console.Write(matrixSolution[row, col]);
                }
                Console.WriteLine();
            }
        }
    }
}

2018/09/06 11:23

mohenjo

#include <stdio.h>
#include <stdlib.h>

void dfs(char**, int, int, int, int);

int main()
{
    int n, m;
    char **arr;
    scanf("%d %d", &n, &m);

    arr = (char**)malloc(sizeof(char*) * (n + 1));
    for (int i = 0; i < n + 1; i++)
        arr[i] = (char*)malloc(sizeof(char) * (m + 1));

    for (int i = 0; i < n; i++)
        scanf("%s", arr[i]);

    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            if (arr[i][j] == '.')
                dfs(arr, m, n, j, i);

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
            printf("%c", arr[i][j]);
        printf("\n");
    }

    for (int i = 0; i < n + 1; i++)
        free(arr[i]);
    free(arr);

    return 0;
}

void dfs(char **arr, int w, int h, int x, int y)
{
    int tx, ty, cnt = 0;
    for (int i = -1; i <= 1; i++)
    {
        for (int j = -1; j <= 1; j++)
        {
            if (i || j)
            {
                tx = x + j, ty = y + i;
                if ((0 <= tx && tx < w && 0 <= ty && ty < h) && arr[ty][tx] == '*')
                    cnt++;
            }
        }
    }
    arr[y][x] = '0' + 1;
}

2018/10/10 14:56

김강산

코딩도장23.7이요

col,row=map(int,input().split())

matrix=[]
for i in range(row):
    matrix.append(list(input()))

for i in range(col):
    for j in range(row):
        if matrix[i][j]=='*':
            continue
        else:
            matrix[i][j]=0
            if matrix[i][j]==0:
                for x in range(i-1,i+2):
                    for y in range(j-1,j+2):
                        if y < 0 or x < 0 or y >= row or x >= col:
                            continue
                        elif matrix[x][y]=='*':
                            matrix[i][j]+=1
                        else:
                            continue

print(matrix)

리스트로 출력되는데 문자열로 출력하는 방법알려주세요

2018/12/21 17:14

yeonhu Ha

시간을 절약하기 위해 주변 지뢰를 세는 것이 아닌 지뢰가 있으면 주변 위치들에 +1을 하게 했습니다.

def plus(yc,xc,mines):

    for y in range(yc-1,yc+2):
        for x in range(xc-1,xc+2):

            if -1<y<len(mines) and -1<x<len(mines[0]) and mines[y][x] != '*':
                mines[y][x] = '1' if mines[y][x] == '.' else str(int(mines[y][x])+1)

    return mines



def mine(m,n):
    mines = []

    for x in range(m):
        mines.append(list(input()))

    for y in range(n):
        for x in range(m):

            if mines[y][x] == '*':
                mines = plus(y,x,mines)
            if mines[y][x] == '.':
                mines[y][x] = '0'

    for x in range(m):
        print(''.join(mines[x]))

2019/01/26 11:54

김영성

import random
row, col = map(int, input().split())
square = []
square = [[random.choice(['.','.','.','.','*']) for i in range(col)] for y in range(row)]

for j in range(row):
    for i in range(col):
        if square[j][i] == '*':
            continue
        else:
            square[j][i] = 0
            for y in range(j - 1, j + 2):
                for x in range(i -1, i + 2):
                    if y < 0 or x < 0 or y >= row or x >= col:
                        continue
                    else:
                        if square[y][x] == '*':
                            square[j][i] += 1

for j in range(row):
    for i in range(col):
        print(square[j][i], end ='')
    print()

2019/01/29 10:14

D.H.

import random

matrix = input("정수 두개 입력 : (예)4 4\n")
m2List = matrix.split()
m = int(m2List[0])
n = int(m2List[1])
land = '□'
mine = '♨'

def enCoord(x, y) : #정수 2개를 좌표 형식 문자열로
    return str(x) + ',' + str(y)

isMine = {} #전체 매트릭스 <= 출력 + 미출력(테두리)
for y in range(0, m + 2) : #지뢰 설치
    for x in range(0, n + 2) :
        coordinate = enCoord(x, y)
        if x == 0 or x == (n + 1) or y == 0 or y == (m + 1) :
            isMine[coordinate] = False
        else :
            randMine = random.randint(1, 6) #지뢰 매설 확률 1/6 임의로 정함
            if randMine == 6 :
                isMine[coordinate] = True
                print(mine, end=' ')
            else :
                isMine[coordinate] = False
                print(land, end=' ')
    print()

for y in range(1, m + 1) : #지뢰 검출
    for x in range(1, n + 1) :
        coordinate = enCoord(x, y)
        if isMine[coordinate] :
            print(mine, end=' ')
        else :
            matrix9 = []
            for miniY in range(y - 1, y + 2) :
                for miniX in range(x - 1, x + 2) :
                    Coord9 = enCoord(miniX, miniY)
                    matrix9.append(isMine[Coord9])
            print(matrix9.count(True), end=' ')
    print()

2019/02/21 23:35

좋은나쎔

C

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int m, n;
    scanf("%d %d", &m, &n);
    char **mat = malloc(sizeof(char *) * (m + 2));
    char *temp = malloc(sizeof(char)*(n + 2));
    for (int i = 0; i < m + 2; i++)
    {
        mat[i] = malloc(sizeof(char) * (n + 2));
        if ((i == 0) || (i == m + 1))
            memset(mat[i], '.', sizeof(char) * (n + 2));
    }
    for (int i = 1; i < m + 1; i++)
    {
        scanf("%s", temp);
        for (int j = 1; j < n + 1; j++)
        {
            mat[i][j] = temp[j - 1];
            mat[i][0] = '.';
            mat[i][n + 1] = '.';
        }
    }
    for (int i = 1; i < m + 1; i++)
    {
        for (int j = 1; j < n + 1; j++)
        {
            char sum = 0;
            if (mat[i][j] == '*')
                continue;
            for (char p = -1; p <= 1; p++)
            {
                for (char q = -1; q <= 1; q++)
                {
                    if (mat[i + p][j + q] == '*')
                        sum += 1;
                }
            }
            mat[i][j] = sum + 48;
        }
    }

    for (int i = 1; i < m + 1; i++)
    {
        for (int j = 1; j < n + 1; j++)
            printf("%c", mat[i][j]);
        printf("\n");
    }
    for (int i = 0; i < m + 2; i++)
        free(mat[i]);
    free(mat);
    free(temp);
    return 0;
}

2019/03/29 13:30

Hyuk

direc = ((-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1))

def writeNumber(board):
    for x in range(m):
        for y in range(n):
            if board[(x,y)] == '.':
                board[(x,y)] = 0
                for dx, dy in direc:
                    nx = x + dx
                    ny = y + dy
                    if 0<=nx<m and 0<=ny<n and board[(nx, ny)] == '*':
                        board[(x,y)] += 1
    display(board)


def display(board):
    for x in range(m):
        _str = ''
        for y in range(n):
            _str = _str + str(board[(x,y)])
        print(_str)


m, n = map(int, input().split())

board = {}
for i in range(m):
    line = input()
    for j in range(n):
        board[(i,j)] = line[j]

writeNumber(board)

2019/04/30 15:51

messi

#include <stdio.h>
#include <string.h>
#define MAX 10

int main(void)
{
    int m,n;
    int i,j;
    char board[MAX][MAX];
    scanf("%d%d",&m,&n);
    fflush(stdin);

    for(i = 0; i<m; i++)
    {
        for(j = 0; j<n; j++)
        {
            scanf("%c",&board[i][j]);
        }
        fflush(stdin);
    }
    for(i = 0; i<m; i++)
    {
        for(j = 0; j<n; j++)
        {
            if(board[i][j] == '.')
            {
                int ho = 0;
                if(board[i+1][j] == '*') {ho++;}
                if(board[i-1][j] == '*') {ho++;}
                if(board[i][j+1] == '*') {ho++;}
                if(board[i][j-1] == '*') {ho++;}

                if(board[i+1][j-1] == '*') {ho++;}
                if(board[i-1][j+1] == '*') {ho++;}
                if(board[i+1][j+1] == '*') {ho++;}
                if(board[i-1][j-1] == '*') {ho++;}

                board[i][j] = 48+ho;
            } 
        }
    }
    printf("\n");
    for(i = 0; i<m; i++)
    {
        for(j = 0; j<n; j++)
        {
            printf("%c",board[i][j]);
        }
        printf("\n");
    }
    return 0;
}

2019/08/11 14:11

RADEAN STUDIO

temp = input("")
string = []
for i in range (len(temp)):
    string.append(temp[i])
temp = string.count(' ')
for i in range(temp):
    string.remove(' ')

col = int(string[0])
row = int(string[1])

board = []

bombs = []

for i in range (col):
    temp = str(input(""))
    while(len(temp) != row):
        temp = str(input("Please try again\n"))
    board.append(list(temp))

for i in range (col):
    for j in range (row):
        if(board[i][j] == '*'):
            bombs.append([i,j])
        else:
            continue
tempCount = 0
for y in range (col):
    for x in range (row):
        if([y,x] not in bombs):
            tempCount = 0
            for i in range(-1, 2):
                for j in range(-1, 2):
                    if(y+i >= 0 and x+j >= 0):
                        if([y+i, x+j] in bombs):
                            tempCount += 1
        if([y,x] not in bombs):
            board[y][x] = tempCount
        tempCount = 0

for i in range(col):
    for j in range(row):
        print(board[i][j], end="")
    print("\n")

2019/08/17 01:34

Hyeonseong Lim

파이썬 코딩 도장 - 23.7 심사문제 풀이 방식입니다.

M,N = map(int,input().split())

matrix = []
for i in range(N):
    matrix.append(list(input()))

for i in range(N):
    for j in range(M):
        if matrix[i][j]=='*':
            print(matrix[i][j],sep='',end='')
        else:
            count = 0
            for x in range(i-1,i+2):
                for y in range(j-1,j+2):
                    if x < 0 or y < 0 or x >= N or y >= M:
                        continue
                    elif matrix[x][y]=='*':
                        count += 1
            print(count, sep='', end='')                          

    print()

2019/09/23 18:06

JJang Kim

import random
inp=input("행(M)과 열(N)을 입력하십시오(ex-4 4): ").split(" ")
matrix=eval(repr([["."]*int(inp[1])]*int(inp[0])))
while True:
    mn=int(input("지뢰의 개수를 입력하십시오: "))
    if mn<=int(inp[0])*int(inp[1]):
        break
    else:
        print("지뢰의 개수가 매트릭스 격자의 수보다 많습니다.")
elst=[]
while len(elst)<mn:
    mx,my=random.randint(0,int(inp[0])-1),random.randint(0,int(inp[1])-1)
    if [mx,my] not in elst:
        elst.append([mx,my])
        matrix[mx][my]="*"
    else:
        continue
for i in range(int(inp[0])):
    for j in range(int(inp[1])):
        if matrix[i][j]!="*":
            matrix[i][j]=0
for k in range(mn):
    i,j=elst[k][0],elst[k][1]
    if 0<=i+1<int(inp[0]) and matrix[i+1][j]!="*":
        matrix[i+1][j]+=1
    if 0<=j+1<int(inp[1]) and matrix[i][j+1]!="*":
        matrix[i][j+1]+=1
    if 0<=i+1<int(inp[0]) and 0<=j+1<int(inp[1]) and matrix[i+1][j+1]!="*":
        matrix[i+1][j+1]+=1
    if 0<=i-1<int(inp[0]) and 0<=j-1<int(inp[1]) and matrix[i-1][j-1]!="*":
        matrix[i-1][j-1]+=1
    if 0<=i-1<int(inp[0]) and 0<=j+1<int(inp[1]) and matrix[i-1][j+1]!="*":
        matrix[i-1][j+1]+=1
    if 0<=i+1<int(inp[0]) and 0<=j-1<int(inp[1]) and matrix[i+1][j-1]!="*":
        matrix[i+1][j-1]+=1
    if 0<=i-1<int(inp[0]) and matrix[i-1][j]!="*":
        matrix[i-1][j]+=1
    if 0<=j-1<int(inp[1]) and matrix[i][j-1]!="*":
        matrix[i][j-1]+=1
for lst in matrix:
    for cmpnt in lst:
        print("%3s"%cmpnt, end="")
    print()

행과 열을 입력하고, 지뢰의 개수를 입력한 뒤 출력(지뢰 위치는 랜덤)

행(M)과 열(N)을 입력하십시오(ex-4 4): 4 4
지뢰의 개수를 입력하십시오: 16
 0  0  1  *
 0  1  2  2
 0  1  *  1
 0  1  1  1

2020/03/26 21:28

박시원

#include <iostream>
#include <string>
using namespace std;
/*
출처 : www.programming-challenges.com

지뢰찾기 게임은 M x N 매트릭스에 위치해 있는 지뢰를 찾는 게임이다.
M x N 매트릭스 상의 격자(square)는 지뢰이거나 지뢰가 아니다.
지뢰 격자는 *로 표시한다. 지뢰가 아닌 격자(square)는 숫자로 표시하며 그 숫자는 인접해 있는 지뢰의 수를 의미한다. 
(격자(sqaure)는 최대 8개의 인접한 지뢰를 가질 수 있다.)

다음은 4x4 매트릭스에서 2개의 지뢰(*)를 표시하는 방법이다.
*...
....
.*..
....

위 경우의 답은 아래와 같다.
*100
2210
1*10
1110

입력
첫번째 줄은 M x N 의 M(행)과 N(열)에 해당되는 숫자이다. N과 M은 0보다 크고 100 이하이다. 
(0< N, M <=100) 그 다음 M개의 줄이 차례로 입력되고 각 줄은 정확하게 N개의 문자가 입력된다. 
지뢰 격자는 *로 표시하며 지뢰가 아닌 격자는 .(dot)로 표시한다.

출력
지뢰(*)를 제외한 나머지 격자의 숫자값을 찾아서 M x N 매트릭스를 출력한다.

예1)
입력
4 4
*...
....
.*..
....
출력
*100
2210
1*10
1110

예2)
입력
3 5
**...
.....
.*...

출력
**100
33200
1*100
*/

bool check(int n, int m, int x, int y) {
    if(x >= 0 && x < n){
        if (y >= 0 && y < m) { return true; }
        else { return false; }
    }
    else { return false; }
}


int main() {
    int n, m;
    char **arr;
    string s;
    while (1) {
        system("cls");
        cout << "=====================지뢰 찾기=======================" << endl;
        cout << "만들 지뢰는 n행 m열의 지뢰이다.(n 과 m을 입력):";
        cin >> n >> m;
        if (n < 0 || n >= 100) { cout << "행은 0행이상 100행 미만이어야합니다." << endl; system("pause"); continue; }
        if (m < 0 || m >= 100) { cout << "열은 0열이상 100열 미만이어야합니다." << endl; system("pause"); continue; }

        arr = new char*[n];
        for (int i = 0; i < n; i++)
            arr[i] = new char[m];

        for (int i = 1; i <= n;) {
            cout << i << "번째 줄에" << m << "개의 지뢰찾기 맵을 구성해주세요.(지뢰:* 지뢰가 아닌곳:.)입력:";
            cin >> s;
            if (s.length() != m) { cout << m << "개의 구성이 아닙니다 다시입력하세요." << endl; continue; }
            for (int j = 0; j < s.length(); j++)
                if (s[j] != '*'&& s[j] != '.') { cout << "맵 구성이 잘못되었습니다." << endl; continue; }

            for (int j = 0; j < s.length(); j++)
                arr[i - 1][j] = s[j];       
            ++i;
        }
        system("cls");
        cout << "==================입력한 지뢰맵====================" << endl << endl;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                cout << arr[i][j] << " ";
            }
            cout << endl;
        }
        cout << endl;
        cout << "결과를 보기위해 ";
        system("pause");
        cout << endl;
        int count;
        for (int i = 0; i < n; i++) {       
            for (int j = 0; j < m; j++) {
                count = 0;
                if (arr[i][j] == '*') { continue; }
                if (check(n, m, i - 1, j - 1)) { if (arr[i - 1][j - 1] == '*') { count++; } }
                if (check(n, m, i - 1, j)) { if (arr[i - 1][j] == '*') { count++; } }
                if (check(n, m, i - 1, j + 1)) { if (arr[i - 1][j + 1] == '*') { count++; } }
                if (check(n, m, i, j - 1)) { if (arr[i][j - 1] == '*') { count++; } }
                if (check(n, m, i, j + 1)) { if (arr[i][j + 1] == '*') { count++; } }
                if (check(n, m, i + 1, j - 1)) { if (arr[i + 1][j - 1] == '*') { count++; } }
                if (check(n, m, i + 1, j)) { if (arr[i + 1][j] == '*') { count++; } }
                if (check(n, m, i + 1, j + 1)) { if (arr[i + 1][j + 1] == '*') { count++; } }
                arr[i][j] = count + '0';
            }
        }
        cout << "==================지뢰맵 해독결과====================" << endl << endl;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                cout << arr[i][j] << " ";
            }
            cout << endl;
        }
        cout << endl;
        break;
    }
    for (int i = 0; i < n; i++)
        delete[] arr[i];
    delete[] arr;
}

2020/04/08 23:51

++C

import numpy as np

row,col=map(int,input().split(" "))
Str=""
for i in range(row):
    Str+=input()
ary=np.array(list(Str)).reshape(row,col)
list_count=[]
for i in range(row):
    for j in range(col):
        count = 0
        if ary[i][j]=="*":
            list_count.append("*")
            continue
        else:
            if i==0:
                if j==0:
                    if ary[i][j+1]=="*":
                        count+=1
                    if ary[i+1][j]=="*":
                        count+=1
                    if ary[i+1][j+1]=="*":
                        count+=1
                elif j==col-1:
                    if ary[i+1][j]=="*":
                        count+=1
                    if ary[i][j-1]=="*":
                        count+=1
                    if ary[i+1][j-1]=="*":
                        count+=1
                else:
                    if ary[i][j+1]=="*":
                        count+=1
                    if ary[i+1][j]=="*":
                        count+=1
                    if ary[i+1][j+1]=="*":
                        count+=1
                    if ary[i+1][j-1]=="*":
                        count+=1
                    if ary[i][j-1]=="*":
                        count+=1
            elif i==row-1:
                if j == 0:
                    if ary[i][j + 1] == "*":
                        count += 1
                    if ary[i - 1][j] == "*":
                        count += 1
                    if ary[i - 1][j + 1] == "*":
                        count += 1
                elif j == col - 1:
                    if ary[i - 1][j] == "*":
                        count += 1
                    if ary[i][j - 1] == "*":
                        count += 1
                    if ary[i - 1][j - 1] == "*":
                        count += 1
                else:
                    if ary[i][j + 1] == "*":
                        count += 1
                    if ary[i - 1][j] == "*":
                        count += 1
                    if ary[i - 1][j + 1] == "*":
                        count += 1
                    if ary[i - 1][j - 1] == "*":
                        count += 1
                    if ary[i][j - 1] == "*":
                        count += 1
            else:
                if j==0:
                    if ary[i-1][j]=="*":
                        count +=1
                    if ary[i-1][j+1]=="*":
                        count +=1
                    if ary[i][j+1]=="*":
                        count +=1
                    if ary[i+1][j]=="*":
                        count +=1
                    if ary[i+1][j+1]=="*":
                        count +=1
                elif j==col-1:
                    if ary[i-1][j] == "*":
                        count += 1
                    if ary[i - 1][j-1] == "*":
                        count += 1
                    if ary[i][j - 1] == "*":
                        count += 1
                    if ary[i + 1][j - 1] == "*":
                        count += 1
                    if ary[i + 1][j] == "*":
                        count += 1
                else:
                    if ary[i - 1][j - 1] == "*":
                        count += 1
                    if ary[i - 1][j] == "*":
                        count += 1
                    if ary[i - 1][j + 1] == "*":
                        count += 1
                    if ary[i][j - 1] == "*":
                        count += 1
                    if ary[i][j + 1] == "*":
                        count += 1
                    if ary[i + 1][j - 1] == "*":
                        count += 1
                    if ary[i + 1][j] == "*":
                        count += 1
                    if ary[i + 1][j + 1] == "*":
                        count += 1
        list_count.append(count)
for I in range(len(list_count)):
    if I%col==0:
        print("")
    print(list_count[I],end="")

2020/04/27 23:22

kim center

#파이썬
#지뢰찾기 게임도 제대로 못해본 제가 이런걸 만들게 되네요
#동작은 하는것 같은데, 짧은 코드로 만드시는 분들 정말 대단 하십니다

from random import *

temp=str(input('가로크기(size_x) 세로크기(size_y)....')).split(' ')
size_x,size_y=int(temp[0]),int(temp[1])

def print_mat(x):                   #매트릭스를 출력해주는 함수
    for i in range (0,size_y):
        for j in range (0,size_x):
            print(x[i][j],end=' ')
        print()

def check_mat(x):                   #매트릭스를 체크하여 주변의 지뢰 갯수를 세어주는 함수
    for i in range (0,size_y):
        for j in range (0,size_x):
            if x[i][j]!='*':
                if j==0:
                    x0=0
                else:
                    x0=j-1

                if j==size_x-1:
                    x1=size_x-1
                else:
                    x1=j+1

                if i==0:
                    y0=0
                else:
                    y0=i-1

                if i==size_y-1:
                    y1=size_y-1
                else:
                    y1=i+1

                mine_sum=0
                for yy in range (y0, y1+1):
                    for xx in range (x0, x1+1):
                        if x[yy][xx]=='*':
                            mine_sum+=1

                x[i][j]=mine_sum

mat=[]
for i in range (0,size_y):          #사이즈에 맞는 매트릭스를 생성하고, '.'을 채우고, 
    temp=[]
    for j in range (0,size_x):
        temp.append('.')
    for k in range (randint(1,2)):  # 랜덤으로 지뢰(*)를 넣는다 (한 행에 0~2개의 지뢰가 들어간다 )
        mine=randint(-2,size_x+1)
        if mine>=0 and mine<size_x:
            temp[mine]='*'
    mat.append(temp)

print ('<Input>')
print_mat (mat)

check_mat(mat)
print ('<Output>')
print_mat (mat)

2020/05/22 11:52

Buckshot

가로크기(size_x) 세로크기(size_y)....3 5 <Input> . . . . . * . . . . . * <Output> 1 2 2 1 * * 1 3 * 0 2 2 0 1 * 가로크기(size_x) 세로크기(size_y)....8 5 <Input> . . . . . * . . * . . . . . . * * . * . . . . . . . * . . . . . . . . . . . * . <Output> 1 1 0 0 1 * 2 1 * 3 1 1 1 1 2 * * 4 * 2 0 0 1 1 1 3 * 2 0 1 1 1 0 1 1 1 0 1 * 1 가로크기(size_x) 세로크기(size_y)....15 15 <Input> . . . * . . * . . . . . . . . . . . . . . . . . . . . * . . * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . . . . . . * . . . . . . . . . . . * . . . . . . * . . . . . . . . . . . . . . . . . . . * . . * . . . . . . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . * * . . . . . . . . . . . * . . . . . . . . . . . . . . . . * . . . . . * * . . . . . . . . . . * . . . . . . . . . . . . . . * . . . . . . . . . . . . . . <Output> 0 0 1 * 1 1 * 1 0 0 0 1 1 1 0 1 1 1 1 1 1 1 1 0 0 0 1 * 1 0 * 1 0 0 0 0 0 0 0 0 0 1 1 1 0 2 2 1 0 0 0 0 1 1 1 0 0 0 0 0 1 * 1 0 1 1 1 1 * 1 0 1 1 1 0 1 1 1 0 1 * 1 1 1 1 0 1 * 1 0 0 1 1 1 2 2 2 0 0 0 0 1 1 1 0 0 1 * 1 1 * 1 0 0 0 1 1 1 0 0 0 1 1 1 1 1 1 0 0 0 1 * 3 2 1 0 0 0 0 0 0 0 0 0 1 2 3 * * 1 0 0 0 0 0 0 0 0 0 1 * 3 3 3 1 0 0 1 2 2 1 0 0 0 1 1 2 * 1 0 1 1 1 * * 1 0 0 0 0 0 1 1 1 0 * 2 1 2 2 1 0 0 0 0 0 0 0 0 0 * 2 0 0 0 0 0 0 0 0 0 0 0 0 0 가로크기(size_x) 세로크기(size_y)....20 20 <Input> . . . * . * . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . . . . * . . . . . . * . . . . . . . . . . . . . . . . . . . . . . . . * . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . . . . * . . . . . . . . . * . . . . . . . . * . * . . . . . . . . . . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . . . . . . * . . * . . . . . . . . . . . * . . . * . . . . . . . . . . . . . * . . . . * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . <Output> 1 1 2 * 2 * 1 0 0 0 0 0 0 0 0 0 0 0 0 0 2 * 3 1 2 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 2 * 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 1 * 1 0 0 1 * 1 0 0 0 0 1 * 1 0 0 1 1 1 1 1 1 0 0 1 1 1 0 0 0 1 2 1 1 0 0 1 * 1 0 0 0 0 0 0 0 0 0 0 0 * 2 1 1 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 0 1 2 * 1 0 0 0 0 0 1 1 2 * 1 0 0 0 0 0 0 1 2 3 2 1 0 0 0 0 1 * 2 1 1 0 0 0 0 0 0 1 * 2 * 1 0 0 1 1 2 1 1 0 0 0 0 0 0 0 0 1 1 2 1 2 1 1 1 * 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 * 2 2 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 2 2 * 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 * 1 1 2 2 1 1 1 1 0 0 0 0 0 0 0 0 0 1 2 2 1 1 2 * 1 1 * 1 0 0 0 0 0 0 0 1 1 2 * 1 1 2 * 2 1 1 1 1 0 0 0 0 0 0 0 1 * 2 1 1 1 * 2 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 - Buckshot, 2020/05/22 11:54
def mine(inp):
    for i in range(len(inp)):
        for j in range(len(inp[i])):
            if inp[i][j] == '.':
                cnt = 0
                for x in range(i-1, (i+2, i+1)[i+2 > len(inp)]):
                    for y in range(j-1, (j+2, j+1)[j+2 > len(inp)]):
                        if inp[x][y] == '*':
                            cnt += 1
                print(cnt, end='')
            else:
                print('*', end='')
        print()

if __name__ == '__main__':
    inp = ['*...',
           '....',
           '.*..',
           '....']
    mine(inp)

2020/06/11 09:25

Hwaseong Nam

2중 반복문 없이 지뢰를 기준으로 이늄 전략패턴을 돌리는 방법입니다. 실력이 모잘라서, 소스가 길어버리네요;;


import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CodingDojangMineSweeper {

    static class Block {
        private static Block OUTOFGAME = new Block(-1, null);
        private final int index;
        private int count;
        private final Game game;
        private boolean mine;

        public Block(int number, Game game) {
            this.index = number;
            this.game = game;
        }

        public int getIndex() {
            return index;
        }

        public int getWidth() {
            return this.game.getWidth();
        }

        public Block getBlock(int index) {
            if (this == Block.OUTOFGAME) return this;
            return this.game.getBlock(index);
        }

        public void plusCount() {
            this.count++;
        }

        public Block layMine() {
            if (this == OUTOFGAME) throw new IllegalStateException("OUTOFGAME Block can't set mine.");
            this.mine = true;
            return this;
        }

        public boolean isInGameBlock() {
            return this != OUTOFGAME;
        }

        @Override
        public String toString() {
            return String.valueOf(this.mine ? "*" : this.count);
        }

        public Set<Block> getAdjacentBlock(MovingStrategy[] strategies) {
            if (this == OUTOFGAME) throw new IllegalStateException("OUTOFGAME Block can't getAdjacentBlock.");
            Set<Block> l = new HashSet<>();
            for (MovingStrategy s : strategies)
                l.add(s.apply(this));
            return l;
        }
    }

    enum MovingStrategy {
        UP(b -> b.getBlock(b.getIndex() - b.getWidth())),
        DOWN(b -> b.getBlock(b.getIndex() + b.getWidth())),
        LEFT(b -> {
            if (!b.isInGameBlock()) return b;
            int index = b.getIndex();
            if (index % b.getWidth() == 0)
                return Block.OUTOFGAME;
            return b.getBlock(index - 1);
        }),
        RIGHT(b -> {
            if (!b.isInGameBlock()) return b;
            int width = b.getWidth();
            int index = b.getIndex();
            if (index % width == (width - 1)) {
                return Block.OUTOFGAME;
            }
            return b.getBlock(index + 1);
        }),
        UPLEFT(UP.strategy.andThen(LEFT.strategy)),
        UPRIGHT(UP.strategy.andThen(RIGHT.strategy)),
        DOWNLEFT(DOWN.strategy.andThen(LEFT.strategy)),
        DOWNRIGHT(DOWN.strategy.andThen(RIGHT.strategy));

        private Function<Block, Block> strategy;

        MovingStrategy(Function<Block, Block> strategy) {
            this.strategy = strategy;
        }

        public Block apply(Block block) {
            return this.strategy.apply(block);
        }

        static MovingStrategy[] getEasyStrategy() {
            return new MovingStrategy[]{UP, DOWN, LEFT, RIGHT};
        }
    }

    static class Game {
        private int width;
        private int height;
        private final List<Block> blocks;

        public Game(GameOption gameOption) {
            this.width = gameOption.getWidth();
            this.height = gameOption.getHeight();
            int size = width * height;

            // set blocks
            this.blocks = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                this.blocks.add(i, new Block(i, this));
            }

            // mines
            Set<Integer> mines = gameOption.getMineNums();
            mines.stream()
                    .map(this::layMine)
                    .map(block -> block.getAdjacentBlock(MovingStrategy.values()))
                    .flatMap(Collection::stream)
                    .filter(Block::isInGameBlock)
                    .forEach(Block::plusCount);

            // .flatMap(block -> Arrays.stream(MovingStrategy.values()).map(s-> s.apply(block)))
        }


        public String toString() {
            String res = "";
            for (int i = 0; i < width * height; i++) {
                res += getBlock(i).toString();
                if (i % getWidth() == (width - 1)) {
                    res += System.getProperty("line.separator");
                }
            }
            return res;
        }

        public void print() {
            System.out.print(toString());
            System.out.println("======================");
        }

        public int getWidth() {
            return this.width;
        }

        Block getBlock(int index) {
            if (index < 0 || index >= width * height) {
                return Block.OUTOFGAME;
            }
            return this.blocks.get(index);
        }

        private Block layMine(int index) {
            return getBlock(index).layMine();
        }

    }

    static class GameOption {
        int width;
        int height;
        Set<Integer> mineNums;

        public GameOption(int width, int height, Set<Integer> mine) {
            this.width = width;
            this.height = height;
            this.mineNums = mine;
        }

        public GameOption(String input) {
            String[] split = input.split("\n");
            String[] s = split[0].split(" ");
            this.width = Integer.parseInt(s[1]);
            this.height = Integer.parseInt(s[0]);
            this.mineNums = new HashSet<>();
            List<String> strings = new ArrayList<>(Arrays.asList(split));
            strings.remove(0);
            String collected = strings.stream().collect(Collectors.joining());
            for (int i = 0; i < collected.length(); i++) {
                if (collected.charAt(i) == '*') {
                    mineNums.add(i);
                }
            }
        }

        public int getWidth() {
            return width;
        }

        public int getHeight() {
            return height;
        }

        public Set<Integer> getMineNums() {
            return mineNums;
        }
    }


    public static Set<Integer> getRandomNumbers(int max) {
        Set<Integer> mine = new HashSet<>();
        int randomSize = (int) (max * 0.2);
        while (mine.size() < randomSize) {
            int i = (int) (Math.random() * (max - 1));
            mine.add(i);
        }
        return mine;
    }


    public static void main(String[] args) {
        String input = """
                4 4
                *...
                ....
                .*..
                ....
                """;
        new Game(new GameOption(input)).print();
        input = """
                3 5
                **...
                .....
                .*...
                """;
        new Game(new GameOption(input)).print();

        System.out.println("25 칸 짜리");
        new Game(new GameOption(5, 5, getRandomNumbers(25))).print();

        System.out.println("49 칸 짜리");
        new Game(new GameOption(7, 7, getRandomNumbers(49))).print();

        System.out.println("100 칸 짜리");
        new Game(new GameOption(10, 10, getRandomNumbers(100))).print();
    }
}

2020/07/31 01:28

최 강용

import random

def sol(m, n, mine) :
    result = ["."*n for i in range(0, m)]
    vec = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
    while mine > 0 :
        minePos = (random.randint(0, m-1), random.randint(0, n-1))
        if result[minePos[0]][minePos[1]] == "." :
            result[minePos[0]] = result[minePos[0]][:minePos[1]]+"*"+result[minePos[0]][minePos[1]+1:]
            mine -= 1
        else : continue
    for p in range(0, m) : print(" ".join(result[p]))
    _result = []
    for y in range(0, m) :
        c = ""
        for x in range(0, n) :
            if result[y][x] == "*" : 
                c += "*"
                continue
            counter = 0
            for lVec in vec :
                if (0<=x+lVec[0]<n) and (0<=y+lVec[1]<m) and (result[y+lVec[1]][x+lVec[0]] == "*") :
                    counter += 1
                else : continue
            c += str(counter)
        _result.append(c)

    print("\n\n")

    for o in range(0, m) : print(" ".join(_result[o]))

if __name__ == "__main__" :
    print(sol(6, 5, 3))

결과

. . . . .
. . . * .
. . . . *
. . . * .
. . . . .
. . . . .



0 0 1 1 1
0 0 1 * 2
0 0 2 3 *
0 0 1 * 2
0 0 1 1 1
0 0 0 0 0
None

2020/09/10 17:44

GG

지뢰를 중심으로 찾는 방법입니다



M,N = map(int, input("두 숫자 입력:").split())
matrix = []
for m in range(M):
    matrix.append(list(input()))

for m in range(M):
    for n in range(N):
        if matrix[m][n] == '*':
            for a in range(-1,2):
                for b in range(-1,2):
                    if (M > m+a >= 0) and (N > n+b >= 0) and matrix[m+a][n+b] != '*':
                        if matrix[m+a][n+b] == '.':
                            matrix[m+a][n+b] = 1
                        else:
                            matrix[m+a][n+b] += 1
        elif matrix[m][n] == '.':
            matrix[m][n] = 0

for m in range(M):
    for n in range(N):
        print(''.join(str(matrix[m][n])),end='')
    print(end='\n')


2020/09/17 09:39

호앙윤

public class Minesweeper {
    private static final int SIZE = 4;
    private static final int MINE = 2;
    private static final String DEFAULT = "·";
    public static void main(String[] args) {
        String data = DEFAULT;
        int x = 0,y = 0,mine_cnt = 0;
        int[][] mineMAP = new int[SIZE][SIZE];

        //지뢰 설치
        while (mine_cnt < MINE) {
            x = new Random().nextInt(SIZE);
            y = new Random().nextInt(SIZE);

            //지뢰 Setting
            for (int i = 0; i < mineMAP.length; i++) {
                for (int j = 0; j < mineMAP[i].length; j++) {
                    if(mineMAP[i][j] != 9) {
                        if((i == x && j == y)) mineMAP[i][j] = 9;//지뢰
                        else if(i == x && (y-1 <= j && j <= y+1)) mineMAP[i][j]++;//지뢰주변(-)
                        else if(j == y && (x-1 <= i && i <= x+1)) mineMAP[i][j]++;//지뢰주변(|)
                        else if((i != x && j != y) && (i == x-1 || i == x+1) && (j == y-1 || j == y+1)) mineMAP[i][j]++;//지뢰주변(X)
                    }
                }
            }
            mine_cnt++;
        }

        //지뢰탐색 맵 출력
        for (int i = 0; i < mineMAP.length; i++) {
            for (int j = 0; j < mineMAP[i].length; j++) {
                if(mineMAP[i][j] == 9) data = "*";
                else if(mineMAP[i][j] == 0) data = DEFAULT;
                else data = Integer.toString(mineMAP[i][j]);
                System.out.print("[" + data + "]");
            }
            System.out.println();
        }
    }
}

2020/09/21 10:25

gunhee0323

input1 = input()
matrix_list = input1.split(' ')
line = int(matrix_list[0])
number = int(matrix_list[1])
matrix = []
mine = []
for i in range(line) :
    inputi = input()
    matrix.append(inputi)
for k in range(line) :
    index = -1
    while True :
        index = matrix[k].find('*', index +1)
        if index == -1 :
            break
        if index >= 0 :
            mine.append((k,index))

for y in range(line) :
    p_line = []
    for x in range(number) :
        mine_number = 0

        if (y,x) in mine :
            p_line.append('*')

        elif y != 0 and y != line-1 and x != 0 and x != number-1 :
            for i in range(3) :
                if (y-1,x-1+i) in mine :
                    mine_number = mine_number + 1
                if (y+1,x-1+i) in mine :
                    mine_number = mine_number + 1
            if (y,x-1) in mine :
                mine_number = mine_number + 1
            if (y,x+1) in mine :
                mine_number = mine_number + 1
            p_line.append(mine_number)

        elif y == 0 and x != 0 and x != number-1 :
            for i in range(3) :
                if (y+1,x-1+i) in mine :
                    mine_number = mine_number + 1
            if (y,x-1) in mine :
                mine_number = mine_number + 1
            if (y,x+1) in mine :
                mine_number = mine_number + 1
            p_line.append(mine_number)

        elif y == line-1 and x != 0 and x != number-1 :
            for i in range(3) :
                if (y-1,x-1+i) in mine :
                    mine_number = mine_number + 1
            if (y,x-1) in mine :
                mine_number = mine_number + 1
            if (y,x+1) in mine :
                mine_number = mine_number + 1
            p_line.append(mine_number)

        elif x == 0 :
            if y != 0 and y != line-1 :
                for i in range(2) :
                    if (y-1,x+i) in mine :
                        mine_number = mine_number + 1
                    if (y+1,x+i) in mine :
                        mine_number = mine_number + 1
                if (y,x+1) in mine :
                    mine_number = mine_number + 1
                p_line.append(mine_number)

            elif y == 0 :
                for i in range(2) :
                    if (y+1,x+i) in mine :
                        mine_number = mine_number + 1
                if (y,x+1) in mine :
                    mine_number = mine_number + 1
                p_line.append(mine_number)

            elif y == line-1 :
                for i in range(2) :
                    if (y-1,x+i) in mine :
                        mine_number = mine_number + 1
                if (y,x+1) in mine :
                    mine_number = mine_number + 1
                p_line.append(mine_number)

        elif x == number-1 :
            if y != 0 and y != line-1 :
                for i in range(2) :
                    if (y-1,x-1+i) in mine :
                        mine_number = mine_number + 1
                    if (y+1,x-1+i) in mine :
                        mine_number = mine_number + 1
                if (y,x-1) in mine :
                    mine_number = mine_number + 1
                p_line.append(mine_number)

            elif y == 0 :
                for i in range(2) :
                    if (y+1,x-1+i) in mine :
                        mine_number = mine_number + 1
                if (y,x-1) in mine :
                    mine_number = mine_number + 1
                p_line.append(mine_number)

            elif y == line-1 :
                for i in range(2) :
                    if (y-1,x-1+i) in mine :
                        mine_number = mine_number + 1
                if (y,x-1) in mine :
                    mine_number = mine_number + 1
                p_line.append(mine_number)



    for i in range(len(p_line)) :
        p_line[i] =  str(p_line[i])
    print(''.join(p_line))

2020/10/23 00:04

Centro

while True:
    MandN=input().split()

    if len(MandN)==2:
        M=int(MandN[0])
        N=int(MandN[1])
        if 0<M<=100 and 0<N<=100:
            break
    else:
        print('다시')

board=[]

print('판을 입력하세요')
for x in range(M):
    board.append(list(input()))

for x in range(M):
    for y in range(N):
        jirae=0
        if board[x][y]=='.':
            for xdirection,ydirection in [[0,1],[0,-1],[1,0],[1,-1],[1,1],[-1,0],[-1,1],[-1,-1]]:
                xstart=x
                ystart=y
                xstart+=xdirection
                ystart+=ydirection
                if xstart>=M or xstart<0 or ystart>=N or ystart<0:
                    continue
                if board[xstart][ystart]=='*':
                    jirae+=1

                continue

            board[x][y]=jirae

for x in range(M):
    for y in range(N):
        print(board[x][y],end='')
    print()

이중 리스트 사용했고 파이썬이에요~!

2020/10/25 21:01

안녕하세요

m, n = map(int, input('Enter M, N: ').split())
q = []
for _ in range(m):
    q.append(list(input()))

for i in range(m): # 1
    for j in range(n): # 1
        if q[i][j] == '*':
            print('*', end='')
        else:
            count = 0
            for x in range(-1, 2):
                for y in range(-1, 2):
                    if 0<=i+x<=m-1 and 0<=j+y<=n-1 and q[i+x][j+y] == '*':
                        count += 1
            print(count, end='')
    print()

2021/02/08 16:24

Ha

def getInput():
    x,y = map(int,(input().split()))

    matrix=[]
    for i in range(x):
        matrix.append(list(input()))

    return(matrix,x,y)


matrix,x,y = getInput()

target_list = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]

for i in range(x):
    for j in range(y):
        if matrix[i][j] == "*":
            continue
        elif matrix[i][j] == ".":
            count=0
            for o,p in target_list:
                try :
                    if matrix[i+o][j+p] == "*" and i+o >= 0 and j+p >=0:
                        count +=1
                except Exception as e:
                    pass
            matrix[i][j] = str(count)
        else:
            print("Wrong data input")

for i in matrix:
    print("".join(i))

2021/04/30 19:28

최태호

import random
#가로,세로,지뢰수
n,m,mine = 4,4,3

#필드초기화
mirror = [[0]*n for _ in range(m)]
ground = [['●']*n for _ in range(m)]

#지뢰 매설
install = 0
while install<mine:
    a = random.randint(0,n-1)
    b = random.randint(0,n-1)
    if ground[a][b] != '※':
        ground[a][b] = '※'
        install+=1

#탐지범위
list = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]
#탐지
for i in range(n):
    for j in range(m):
        for e in list:
            if ground[i][j]=='※' and 0<=i+e[0]<n and 0<=j+e[1]<m:
                mirror[i+e[0]][j+e[1]]+=1
#결과
for i in range(m):
    print(ground[i])

for i in range(m):
    print(mirror[i])

2021/06/29 10:56

약사의혼자말

import random
while True:
    m=int(input('M 값을 입력해주세요: '))
    n=int(input('N 값을 입력해주세요: '))
    if 0<m<=100 and 0<n<=100:
        break
    else:
        print('0< m,n <= 100 이 되도록 입력해주세요')
mine=[]
for i in range(n):
    for j in range(m):
        mine.append(random.choice('....*'))
user=[]
x=0
for k in range(m):
    for l in range(n):
        save=[]
        if mine[x]=='*':
            user.append(mine[x])
        else:
            if k>=1:
                save.append(mine[x-n])
                if x-(n+1)>=0 and (x-(n+1))/n>=k-1:
                    save.append(mine[x-(n+1)])
                if x-n+1>=1 and (x-n+1)/n<k:
                    save.append(mine[x-n+1])
            if x-1>=0 and x/n>k:
                save.append(mine[x-1])
            if x+1<=m*n-1 and (x+2)/n<=k+1:
                save.append(mine[x+1])
            if k+1<m:
                save.append(mine[x+n])
                if x+(n-1)<=m*n-2 and (x+(n-1))/n>=k+1:
                    save.append(mine[x+(n-1)])
                if x+(n+1)<=m*n-1 and k+2>(x+(n+1))/n>k+1:
                    save.append(mine[x+n+1])
            user.append(save.count('*'))
        x+=1
p=''
for a in range(m*n):
    p+=str(user[a])
    if (a+1)%n==0:
        p+='\n'
print(p)

2021/08/08 23:38

Percy

package justStudying;


public class test5_20210822 {

    public static void sol(int m, int n, String box[][]) {
        Integer res[][] = new Integer[box.length][];

        for(int i=0; i<box.length; i++) {
            res[i] = new Integer[box[i].length];
            for(int j=0; j<box[i].length; j++) {
                switch(box[i][j]) {
                case "*":
                    res[i][j] = -1;
                    break;
                case ".":
                    res[i][j] = 0;
                    break;
                }
            }
        }


        for(int i=0; i<res.length; i++) {
            for(int j=0; j<res[i].length; j++) {
                if(res[i][j] == -1) {
                    if(i-1 >= 0) {
                        if(j-1 >= 0 && res[i-1][j-1] != -1) res[i-1][j-1]++;
                        if(res[i-1][j] != -1) res[i-1][j]++;
                        if(j+1 < res[i].length && res[i-1][j+1] != -1) res[i-1][j+1]++;
                    }
                    if(i+1 < res.length) {
                        if(j-1 >= 0 && res[i+1][j-1] != -1) res[i+1][j-1]++;
                        if(res[i+1][j] != -1) res[i+1][j]++;
                        if(j+1 < res[i].length && res[i+1][j+1] != -1) res[i+1][j+1]++;
                    }

                    if(j-1 >=0 && res[i][j-1] != -1) res[i][j-1]++;
                    if(j+1 < res[i].length && res[i][j+1] != -1) res[i][j+1]++;
                }
            }
        }

        for(int i=0; i<res.length; i++) {
            for(int j=0; j<res[i].length; j++) {
                System.out.print(res[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int m = 4;
        int n = 4;
        String box[][] = {{"*",".",".","."}
                        ,{".",".",".","."}
                        ,{".","*",".","."}
                        ,{".",".",".","."}};
        sol(m,n,box);
    }

}

2021/08/22 18:38

이병호

// Rust

// 지뢰 위치를 기준으로, +1 해줄 범위만 잡아주면 되네요(특히 Rust는 인덱스 변수의 usize 타입 검사를 엄격하게 해서..)

fn mine_sweeper() {

// let arr = "*...
// ....
// .*..
// ....";
let arr = "**...
.....
.*...";

let mut mines = vec![];
for line in arr.lines() {
    mines.push(line.trim().chars().collect::<Vec<char>>());
}

let mut nums = vec![vec![0; mines[0].len()];mines.len()];

for (i, line) in mines.iter().enumerate() {
    for (j, ch) in line.iter().enumerate() {
        if *ch != '*' { continue; }
        let vl = if i > 0 { 1 } else { 0 };
        let vh = if i < mines.len() - 1 { 1 } else { 0 };
        let hl = if j > 0 { 1} else { 0 };
        let hh = if j < mines[i].len() - 1 { 1 } else { 0 };
        for v in (i-vl)..=(i+vh) {
            for h in (j-hl)..=(j+hh) {
                nums[v][h] += 1;
            }
        }
    }
}
println!("{:?}", nums);

}

2022/01/31 13:15

JW KIM

코딩도장 책보고 도전해봅니다. 지뢰 매트릭스 가장자리 부분 처리를 어떻게 할까 고민하다가 상하좌우 한칸씩 더 늘려서 더 큰 매트릭스를 만들고 그 중간에 원래 매트릭스를 집어넣는 방식으로 했습니다. 출력할때는 원래 매트릭스 부분만 나오도록 했습니다.

row, col = map(int, input().split()) # 맵 크기 설정 

matrix = []
for r in range(row):
    k = input()
    while len(k) != col:
        k = input()
    matrix.append(list(k)) # 맵 그리기 (Mine = *, Mine x = .)

# matrix[row][col]
# 예시 출력꼴 matrix[0~2][0~2] = [[*..], [.*.], [*.*]]

matrix_up = [] 
for r in range(row+2):
    line = []
    for c in range(col+2):
        line.append(0)
    matrix_up.append(line)

# 사이즈업한 매트릭스 만듬 / 3*4 -> 5*6 모두 0으로 설정

for r in range(row):
    for c in range(col):
        if matrix[r][c] == '*':
            matrix_up[r+1][c+1] = '*'

# 사이즈업한 매트릭스에 '*'부분 채워 넣음

for r in range(1, row+1):
    for c in range(1, col+1):
        if matrix_up[r][c] == '*':
# 중간에 있는 원래 메트릭스에 있는 지뢰를 대상으로

            for i in range(r-1, r+2):
                for j in range(c-1, c+2):
                    if matrix_up[i][j] != '*':
                        matrix_up[i][j] += 1
#상하(r)좌우(c) 오차 1씩 *가 아니면(지뢰가 아니면) 그 자리에 더하기 1

for r in range(1, row+1):
    output = ''
    for c in range(1, col+1):
        output = output+str(matrix_up[r][c])
    print(output)
# 중간에 있는 원래 매트릭스만 출력



2022/02/05 13:37

이승일

n = list(map(int,input("행x열 입력:").split(" ")))
row= n[0]
column= n[1]

arr=[]
for k in range(row):
        print(k+1,'열 입력')
        while True:
            r = input()
            if len(r)==column:
                arr.append(list(r))
                break

result=[[0 for _ in range(column)] for _ in range(row)]

def limit(a,n):
    if a<1:
        return 0
    elif a>n:
        return n
    else:
        return a
star = []
for j in range(row):
    for k in range(column):
        if arr[j][k]=='*':
            star.append([j,k])
            for l in range(limit(j-1,row),limit(j+2,row)):
                for m in range(limit(k-1,column),limit(k+2,column)):
                    result[l][m] +=1
for k in star:
    result[k[0]][k[1]] = '*'

print(result)

for j in result:
    for i in j:
        print(i,end='')
    print('')

2022/02/12 01:13

양캠부부

# Codingdojang 34
from itertools import product
import random as rd
import numpy as np
# 행렬 크기와 폭타의 수를 define
input_n_m=input("생성하고자 하는 행렬(N X M)을 입력하세요.:")
boom_num=input("폭탄 숫자를 입력하세요:")
boom_num=int(boom_num)
input_list_tem=input_n_m.split()
input_list=[int(i) for i in input_list_tem]
n_address=[int(a) for a in range(0,input_list[0])]
m_address=[int(b) for b in range(0,input_list[1])]
n_m_add=list(product(n_address,m_address))
boom_plase=rd.sample(n_m_add,boom_num)

result=np.zeros((input_list[0],input_list[1]),dtype="S")
result_bm_num=np.zeros((input_list[0],input_list[1]),dtype="S")
#result=[str(y) for y in result_tem]
for i in range(0,input_list[0]):
    for j in range(0,input_list[1]):
        if (i,j) in boom_plase:
            result[i][j]='*'
        else:
            result[i][j]='.'

for i in range(0,input_list[0]):
    for j in range(0,input_list[1]):
#        sample=[]
        if i==0 and j==0 and result[i][j]==b'.':
            sample=[]
            sample.append([result[i][j+1],result[i+1][j],result[i+1][j+1]])
            boom_num_1=np.char.count(sample,b'*')
            boom_sum=np.sum(boom_num_1)
            result_bm_num[i][j]=boom_sum

        elif result[i][j]==b'*':
            result_bm_num[i][j]='*'

        elif input_list[0]-1>i>0 and j==0 and result[i][j]==b'.':
            sample=[]
            sample.append([result[i-1][j],result[i-1][j+1],result[i][j+1],result[i+1][j],result[i+1][j+1]])
            boom_num_1=np.char.count(sample,b'*')
            boom_sum=np.sum(boom_num_1)
            result_bm_num[i][j]=boom_sum

        elif i==0 and input_list[1]-1>j>0 and result[i][j]==b'.':
            sample=[]
            sample.append([result[i][j-1],result[i][j+1],result[i+1][j-1],result[i+1][j],result[i+1][j+1]])
            boom_num_1=np.char.count(sample,b'*')
            boom_sum=np.sum(boom_num_1)
            result_bm_num[i][j]=boom_sum

        elif input_list[0]-1>i>0 and input_list[1]-1>j>0 and result[i][j]==b'.':
            sample=[]
            sample.append([result[i-1][j-1],result[i-1][j],result[i-1][j+1],result[i][j-1],result[i][j+1],result[i+1][j-1],result[i+1][j],result[i+1][j+1]])
            boom_num_1=np.char.count(sample,b'*')
            boom_sum=np.sum(boom_num_1)
            result_bm_num[i][j]=boom_sum


        elif i==0 and j==input_list[1]-1 and result[i][j]==b'.':
            sample=[]
            sample.append([result[i][j-1],result[i+1][j-1],result[i+1][j]])
            boom_num_1=np.char.count(sample,b'*')
            boom_sum=np.sum(boom_num_1)
            result_bm_num[i][j]=boom_sum

        elif input_list[0]-1>i>0 and j==input_list[1]-1 and result[i][j]==b'.':
            sample=[]
            sample.append([result[i-1][j-1],result[i-1][j],result[i][j-1],result[i+1][j-1],result[i+1][j]])
            boom_num_1=np.char.count(sample,b'*')
            boom_sum=np.sum(boom_num_1)
            result_bm_num[i][j]=boom_sum

        elif i==input_list[0]-1 and j==input_list[1]-1 and result[i][j]==b'.':
            sample=[]
            sample.append([result[i-1][j-1],result[i-1][j],result[i][j-1]])
            boom_num_1=np.char.count(sample,b'*')
            boom_sum=np.sum(boom_num_1)
            result_bm_num[i][j]=boom_sum

        elif i==input_list[0]-1 and j==0 and result[i][j]==b'.':
            sample=[]
            sample.append([result[i-1][j],result[i-1][j+1],result[i][j+1]])
            boom_num_1=np.char.count(sample,b'*')
            boom_sum=np.sum(boom_num_1)
            result_bm_num[i][j]=boom_sum

        elif i==input_list[0]-1 and input_list[1]-1>j>0 and result[i][j]==b'.':
            sample=[]
            sample.append([result[i-1][j-1],result[i-1][j],result[i-1][j+1],result[i][j-1],result[i][j+1]])
            boom_num_1=np.char.count(sample,b'*')
            boom_sum=np.sum(boom_num_1)
            result_bm_num[i][j]=boom_sum  

# 답은 찾았지만, 좀 더 효율적인 방법을 찾아봐야겠네요.

2022/08/29 23:59

나무늘보

col, row=map(int, input().split()) # 첫째 줄에서 col, row 개수 받기
matrix = []                        # 빈 행렬 만들기
for i in range(row):
    matrix.append(list(input())) # 둘째 줄에서 input의 list를 뽑고 반복하여 append하기
extmat=[['.']*(col+2) for j in range(row+2)] # 빈칸 한칸씩 양 옆으로 확장시킨 행렬 생성
for b in range(row):
    for a in range(col):
        extmat[b+1][a+1]=matrix[b][a]
answer = []
for y in range(row):
    for x in range(col):
        if matrix[y][x] == '*': # 행렬의 각 성분이 지뢰면 지뢰로 출력
            print('*', end='')
        else: # 행렬의 각 성분이 빈칸이면 대각선포함 근방 지뢰 수 출력
            neighborhood = [[extmat[ny][nx] for nx in range(x,x+3)]for ny in range(y,y+3)] # 확장행렬로 근방행렬 정의
            print(neighborhood[0].count('*')+neighborhood[1].count('*')+neighborhood[2].count('*'), end='') # 근방행렬 카운트
    print()

2023/06/01 15:59

Hanbit Seo

import random

def print_map(M,N,mine_map):
    for m in range(M):
        for n in range(N):
            print(' %s' %mine_map[m][n], end='')
        print()

def make_mine_map(M,N,L):
    mine_map = [['.' for _ in range(N)] for _ in range(M)]

    while L>0:
        r = random.randint(0, M-1)
        c = random.randint(0, N-1)
        if mine_map[r][c]=='.':
            mine_map[r][c] = '*'
            L -= 1    
    return mine_map

def count_mine(m,n,M,N,mine_map):
    dr = [-1,-1,0,1,1,1,0,-1]
    dc = [0,1,1,1,0,-1,-1,-1]
    cnt = 0
    for i in range(8):
        R, C = m+dr[i], n+dc[i]
        if 0<=R<M and 0<=C<N and mine_map[R][C]=='*':
            cnt += 1
    return cnt

def num_of_grid(M,N,mine_map):
    for m in range(M):
        for n in range(N):
            if mine_map[m][n] == ".":
                mine_map[m][n] = count_mine(m,n,M,N,mine_map)

    print('\n', ' =' * 3, ' 출력')
    print_map(M, N, mine_map)


M = int(input(" M(행): "))
N = int(input(" N(열): "))
L = int(input(" 지뢰 수: "))
mine_map = make_mine_map(M,N,L)
print_map(M, N, mine_map)
num_of_grid(M, N, mine_map)

2024/01/19 19:04

insperChoi

JAVA입니다.

package question3.지뢰찾기;

import java.util.Scanner;

public class MineSweeper {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String[] setting = sc.nextLine().split(" ");
        int m = Integer.parseInt(setting[0]);
        int n = Integer.parseInt(setting[1]);

        int[][] map = new int[m][n];

        for (int i = 0; i < m; i++) {
            char[] input = sc.nextLine().toCharArray();
            for (int j = 0; j < input.length; j++) {
                if(input[j] == '*') {
                    map[i][j] = -1;
                    addNum(i+1, j, map);
                    addNum(i, j+1, map);
                    addNum(i-1, j, map);
                    addNum(i, j-1, map);
                    addNum(i+1, j+1, map);
                    addNum(i+1, j-1, map);
                    addNum(i-1, j+1, map);
                    addNum(i-1, j-1, map);
                }
            }
        }

        for (int[] is : map) {
            for (int i : is) {
                System.out.print((i == -1) ? "*" : i);
            }
            System.out.println("");
        }

        sc.close();
    }

    static void addNum(int i, int j, int[][] map) {
        try {
            if(map[i][j] != -1) {
                map[i][j] += 1;
            }
        }
        catch (ArrayIndexOutOfBoundsException e) {

        }
    }
}

2025/02/09 23:17

박준우

목록으로