본문 바로가기

Programing/알고리즘

알고리즘 트레이닝 북 지뢰찾기


// Minesweeper.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//

#include "stdafx.h"
#include <Windows.h>
#include <iostream>

using namespace std;


//해당배열의 주위 지룃수를 리턴함
int calc(int xsize ,char* tarr, int x, int y)
{

 // 특정 배열 구역을 찾음.
 char* arr = tarr + x + (xsize * y) ;

 if( (*arr) == '*' )
  return 9;

 int MineCnt = 0;
 // 그 특정 구역역 주위를 검색.
 //예외처리


 if( *(arr - 1) == '*' )
  MineCnt++;
 if( *(arr + 1) == '*' )
  MineCnt++;

 if( *(arr + (xsize* 1)) == '*' )
  MineCnt++;
 if( *(arr - (xsize* 1)) == '*' )
  MineCnt++;

 if( *(arr -1 - ( xsize* 1)  ) == '*')
  MineCnt++;
 if( *(arr -1 + ( xsize* 1)  ) == '*')
  MineCnt++;
 if( *(arr + 1 + ( xsize* 1)  ) == '*')
  MineCnt++;
 if( *(arr + 1 - ( xsize* 1)  ) == '*')
  MineCnt++;

 

 return MineCnt;
}


int _tmain(int argc, _TCHAR* argv[])
{
 int x= 0, y =0;


 cin >> x >>y;

 cout<< "x : "<<x << " y :"<<y <<endl;

 //x축 공간 +2만큼 더잡음
 int xsize = x+2;
 

 int mallocSize = (x+2)*(y+2); // 이렇게 하는이유는
 /*
 00000 ->y축+1
 0*..0
 0**.0
 0*.*0 ->0이 2개로 x축도 +2
 00000 ->y축+1
 포인터연산으로 접근할때 참조에러 일어나지 않도록...
  */

 char* arr = new char[ mallocSize ];
 memset( arr, 0x00, mallocSize );


 cout<<"정해진 행만큼 지뢰입력"<<endl;

 //input code
 for(int i = 1; i<= y; ++i)
 {
  for(int j = 1 ; j<= x; ++j)
  {
   cin>> *(arr + j + ( xsize*i ) );
  }

 }

 cout<<endl;
 // input confirm
 for(int i = 1; i<= y; ++i)
 {
  for(int j = 1 ; j<= x; ++j)
  {

   cout<< *(arr + j + ( xsize*i ) );
  }
  cout<<endl;
 }

 cout<<endl;
 //calc
 int* arr2 = new int[ mallocSize ];
 
 for(int i = 1; i<= y; ++i)
 {
  for(int j = 1 ; j<= x; ++j)
  {
   int temp=0;
   temp = calc( xsize, arr, j,i);

   *(arr2 + j +( xsize* i) ) = (int)temp;

  }
 }


 // print code
 for(int i = 1; i<= y; ++i)
 {
  for(int j = 1 ; j<= x; ++j)
  {

   cout<< *(arr2 + j + ( xsize*i ) );
  }
  cout<<endl;
 }

 return 0;
}

 

'Programing > 알고리즘' 카테고리의 다른 글

The Trip  (0) 2011.12.05
알고리즘 트레이닝 북 3n+1 문제  (0) 2011.12.05