백준 2210 숫자판 점프(BFS)

choiyongheon·2021년 7월 23일
1

이 문제는 경우의 수가 너무 많아서 n=5의 형태로 주어진 것 같다.
6글자로 글자를 이어붙일 때, 모든 경우의 수를 계산해야하는데 중복이 많기 때문에 set을 이용해야 한다. (중복을 계산하는 문제는 set을 먼저 떠올리게 된다, 또한 점프를 해서 경우의 수가 많을 것 같다면 BFS로 푸는 방법을 떠올리게 된다.)

#include <iostream>
#include <queue>
#include <set>
#include <tuple>
using namespace std;

queue<int> que;
string n;
int map[5][5];
int mx[] = { 1,-1,0,0 };
int my[] = { 0,0,-1,1 };
set<string> s;

void bfs(int x, int y) {
	queue<tuple<int, int , string>> que;
	que.push({ x, y, to_string(map[x][y]) });

	while (!que.empty()) {
		tie(x,y,n) = que.front();
		que.pop();

		 for (int i = 0; i < 4; i++) {
			 int dx = mx[i] + x;
			 int dy = my[i] + y;
			 if (dx >= 5 || dy >= 5 || dx < 0 || dy < 0)	continue;
			
			 string input = n + to_string(map[dx][dy]);
			 if (input.length() == 6)
				 s.insert(input);
			 else
				 que.push({ dx,dy,input });
		 }
		 
	}
}

int main(void) {
	for (int i = 0; i < 5; i++) {
		for (int j = 0; j < 5; j++) {
			cin >> map[i][j];
		}
	}

	for (int i = 0; i < 5; i++) {
		for (int j = 0; j < 5; j++) {
			bfs(i, j);
		}
	}
	cout << s.size() << endl;

}

tuple을 사용하여 좌표 x,y와 map[x][y]를 담아주는 것이 좋다.

profile
주니어 백엔드 개발자

0개의 댓글

관련 채용 정보