백준 17129 c++

magicdrill·2024년 4월 10일
0

백준 문제풀이

목록 보기
280/655

백준 17129 c++

간단한 DFS문제이다. find_answer함수가 DFS함수를 수행한 후 결과를 받아 출력할 생각이었는데 그냥 DFS내에서 출력해버렸다...

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

vector <vector<int>> infoisland;
vector <vector<bool>> visited;
int family_start_x, family_start_y;
int n, m;

void input_infoisland()
{
	int i, j;
	string str;

	cin >> n >> m;
	infoisland.resize(n, vector<int>(m, 0));
	visited.resize(n, vector<bool>(m, false));
	for (i = 0; i < n; i++)
	{
		cin >> str;
		for (j = 0; j < m; j++)
		{
			infoisland[i][j] = str[j] - '0';
			if (infoisland[i][j] == 2)
			{
				family_start_x = j;
				family_start_y = i;
			}
		}
	}

	/*for (i = 0; i < n; i++)
	{
		for (j = 0; j < m; j++)
		{
			cout << infoisland[i][j] << " ";
		}
		cout << "\n";
	}*/
}

void DFS(int start_x, int start_y)
{
	int count = 0;
	int current_x, current_y, next_x, next_y;
	queue <pair<int, int>> q;
	vector<pair<int, int>> direction{ {1, 0},{0, 1},{-1, 0},{0, -1} };
	int i, j, d_size = direction.size(), q_size;

	q.push({ family_start_x, family_start_y });
	visited[family_start_y][family_start_x] = true;
	while (!q.empty())
	{
		q_size = q.size();
		for (i = 0; i < q_size; i++)
		{
			current_x = q.front().first;
			current_y = q.front().second;
			q.pop();
			for (j = 0; j < d_size; j++)
			{
				next_x = current_x + direction[j].first;
				next_y = current_y + direction[j].second;
				if ((next_x >= 0 && next_x < m) && (next_y >= 0 && next_y < n) 
					&& visited[next_y][next_x] == false 
					&& infoisland[next_y][next_x] != 1)
				{
					//뭘 먹는지는 파악 안해도 됨
					if (infoisland[next_y][next_x] == 0)
					{
						q.push({ next_x, next_y });
						visited[next_y][next_x] = true;
					}
					else//3,4,5
					{
						cout << "TAK\n";
						cout << count + 1 << "\n";
						return;
					}
				}
			}
		}
		count++;
	}
	cout << "NIE\n";

	return;
}

void find_answer()
{
	DFS(family_start_x, family_start_y);
}

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	input_infoisland();
	find_answer();

	return 0;
}

0개의 댓글