12100. 2048(Easy)

phoenixKim·2022년 9월 29일
0

백준 알고리즘

목록 보기
135/174

위로 움직이는 거만 만듦.

#include <iostream>
#include <vector>
#include <string>
using namespace std;

// 2048 easy
// 19:13 ~ 

int v[21][21];

int dy[]{ -1,1,0,0 };
int dx[]{ 0,0,-1,1 };

// 한번 합쳐진 도형의 경우, 다시 한번 합쳐지면 안됨.
// 불변수 필요하다고 생각됨.
bool check[21][21];

const int UP = 0;
const int DOWN = 1;
const int LEFT = 2;
const int RIGHT = 4;

// 상하좌우 : 0 1 2 3
void dfs(int y, int x , int dir)
{
	int nextY = y + dy[dir];
	int nextX = x + dx[dir];
	
	if (nextY < 0 || nextY >= 20
		|| nextX < 0 || nextX >= 20)
		return;

	if (v[nextY][nextX] == 0)
	{
		v[nextY][nextX] = v[y][x];
		v[y][x] = 0;
	}
	else if (v[nextY][nextX] == v[y][x]
		&& check[nextY][nextX] == false)
	{
		v[nextY][nextX] *= 2;
		v[y][x] = 0;
		check[nextY][nextX] = true;
		return;
	}
	dfs(nextY, nextX, dir);
}

int main()
{
	int n;
	cin >> n;

	
	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			cin >> v[i][j];
		}
	}

	// up일 경우에는 
	// [1][0] 부터 확인 [2][0] 확인 [3][0] 확인 

	cout << "right move" << endl;
	for (int i = 0; i < n; ++i)
	{
		for (int j = 1; j < n; ++j)
		{
			if (v[j][i] != 0)
			{				
				dfs(j, i , 0);
			}
		}
	}

	// 한번 하고 난 이후에는 체크 변수 초기화하자.

	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			cout << v[i][j] << " ";
		}
		cout << endl;
	}


	cout << "위로 이동" << endl;
	for (int i = 0; i < n; ++i)
	{
		for (int j = 1; j < n; ++j)
		{
			if (v[j][i] != 0)
			{
				
				dfs(j, i, 0);
			}
		}
	}

	// 한번 하고 난 이후에는 체크 변수 초기화하자.

	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			cout << v[i][j] << " ";
		}
		cout << endl;
	}

}

개선할 부분

: 상하좌우로 4번 이동이 가능하고, 이거를 총 5회 실시했을 때의
가장 큰 블록의 값을 구하는 것이므로,

  • 상하좌우를 재귀로 수행할 수 있는 함수를 만들어야 함.
profile
🔥🔥🔥

0개의 댓글

관련 채용 정보