알고리즘 문제풀기/인프런 강의 정답

71. 송아지 찾기 (BFS : 상태트리탐색)

코다람쥐 2022. 5. 19. 14:43

나의정답.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>

using namespace std;

int main(int argc, char** argv) {
	//freopen("input.txt", "rt", stdin);
	int myPos, cowPos, ch[10001] = { 0 }, dis[10001], x, p;
	int op[3] = { 1, -1, 5 };
	queue<int> q;
	scanf("%d %d", &myPos, &cowPos);

	q.push(myPos);
	ch[myPos] = 1;
	dis[myPos] = 0;

	while (!q.empty()) {
		x = q.front();
		q.pop();

		for (int i = 0; i < sizeof(op) / sizeof(int); i++) {
			p = x + op[i];
			if(p < 0 || p > 10000) continue;
			if (p == cowPos) {
				dis[p] = dis[x] + 1;
				printf("%d", dis[p]);
				return 0;
			}

			if (ch[p] == 0) {
				ch[p] = 1;
				dis[p] = dis[x] + 1;				
				q.push(p);
			}
		}
	}

	return 0;
}