-
BOJ 9019 [DSLR]알고리즘 풀이/BFS(너비 우선 탐색) 2018. 9. 18. 04:11
BOJ DSLR : https://www.acmicpc.net/problem/9019
안녕하세요. 이번 문제는 백준 온라인 저지의 DSLR입니다.
문제 해결방법은 다음과 같습니다.
1. 노드 생성(레지스터에 저장되는 10진수, 처음 숫자로부터 해당 10진수까지 가는 명령어의 경로)
2. 각 명령어(D, S, L, R)로 인해 생성되는 정수와 경로를 큐에 저장.
3. 목표 정수가 나오면 리턴.
위와 같은 방법을 사용했더니, 문제는 통과했지만, 메모리와 시간을 많이 사용했습니다.
더 효율적인 방법이 있는지 찾아봐야겠습니다.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103#include <iostream>#include <queue>using namespace std;class Node {public:int Num;string str;Node(int n, string s) {Num = n;str = s;}};queue<Node> q;int ch[4];string str_temp;int ori, dest;bool Visited[10000];int shift_reg(int num, int command) {int result = 0;ch[0] = num / 1000;ch[1] = (num - ch[0] * 1000) / 100;ch[2] = (num - ch[0] * 1000 - ch[1] * 100) / 10;ch[3] = num - ch[0] * 1000 - ch[1] * 100 - ch[2] * 10;switch(command) {case 0: { //left <<int temp = ch[0];ch[0] = ch[1];ch[1] = ch[2];ch[2] = ch[3];ch[3] = temp;break;}case 1: { // right >>int temp = ch[3];ch[3] = ch[2];ch[2] = ch[1];ch[1] = ch[0];ch[0] = temp;break;}}result = ch[0] * 1000 + ch[1] * 100 + ch[2] * 10 + ch[3];return result;}string BFS() {while(!q.empty()) {Node node = q.front();q.pop();int num = node.Num;if(num == dest) {while(!q.empty())q.pop();return node.str;}if(!Visited[(num * 2) % 10000]) {Visited[(num * 2) % 10000] = true;string str = node.str + "D";Node new_node((num * 2) % 10000, str);q.push(new_node);}int temp = 0;if(num - 1 < 0)temp = 9999;elsetemp = num - 1;if(!Visited[temp]) {Visited[temp] = true;string str = node.str + "S";Node new_node(temp, str);q.push(new_node);}int left_num = shift_reg(num, 0);int right_num = shift_reg(num, 1);if(!Visited[left_num]) {Visited[left_num] = true;string str = node.str + "L";Node new_node(left_num, str);q.push(new_node);}if(!Visited[right_num]) {Visited[right_num] = true;string str = node.str + "R";Node new_node(right_num , str);q.push(new_node);}}return "";}int main() {int T;cin >> T;for(int test_case = 1; test_case <= T; test_case++) {cin >> ori >> dest;Node first_node(ori, "");q.push(first_node);Visited[ori] = true;cout << BFS() << endl;for(int i=0; i<10000; i++)Visited[i] = false;}return 0;}cs 반응형'알고리즘 풀이 > BFS(너비 우선 탐색)' 카테고리의 다른 글
BOJ 2146 [다리 만들기] (2) 2018.10.04 BOJ 1726 [로봇] (0) 2018.10.04 BOJ 2234 [성곽] (0) 2018.10.02 BOJ 1600 [말이 되고픈 원숭이] (3) 2018.09.23 SWEA 5653 [줄기세포배양] (3) 2018.09.22