백준 - 2178 미로 탐색

phoenixKim·2021년 9월 14일
0

백준 알고리즘

목록 보기
15/174

문제로!

https://www.acmicpc.net/problem/2178

알아야 할점.

1) 입력값이 띄어쓰기가 없고, 늘어져있음. -> string으로 입력받자.
2) | 또는 의미 : 둘중에 하나만 맞아도 됨.

최근 코드

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

//상하좌우 
int dx[]{ 0,0,-1,1 };
int dy[]{ -1,1,0,0 };
int n, m;

void bfs(vector<vector<bool>>&_check,
	vector<vector<int>>&_v)
{
	queue<pair<int, int>>q;
	q.push(make_pair(0, 0));

	while (!q.empty())
	{
		int curY = q.front().first;
		int curX = q.front().second;
		q.pop();
		_check[curY][curX] = true;

		if (curX == n - 1 && curY == m - 1)
			return;

		for (int i = 0; i < 4; ++i)
		{
			int nY = curY + dy[i];
			int nX = curX + dx[i];


			// 220813 여기서 틀림.
			if (0 <= nY && nY < n
				&& 0 <= nX && nX < m)
				//if (0 <= nY && nY < n
				//	|| 0 <= nX && nX < m)
			{
				if (_check[nY][nX] == true)
					continue;
				// 220813 출력해보고 나니까 여기서 이상하다는 것을 
				// 느낌.
				if (_v[nY][nX] != 1)
					continue;

				q.push(make_pair(nY, nX));
				_v[nY][nX] = _v[curY][curX] + 1;
			}



		}


	}


}


int main()
{
	//freopen("input.txt", "r", stdin);

	cin >> n >> m;

	vector<vector<int>>v(n, vector<int>(m));
	vector<vector<bool>>check(n, vector<bool>(m, false));


	for (int i = 0; i < n; ++i)
	{
		string s; 
		cin >> s;

		for (int j = 0; j < m; ++j)
		{
			v[i][j] = s[j] - '0';
		}
	}

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

	cout << v[n - 1][m - 1];

}

소스코드

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


int main() {

	int answer = -1;
	int n, m;
	cin >> n >> m;

	vector<vector<int>> v(n, vector<int>(m, 0));
	vector<vector<bool>>check(n, vector<bool>(m, 0));
	for (int i = 0; i < n; i++)
	{
		string word;
		cin >> word;
		for (int j = 0; j < m; j++)
		{
			v[i][j] = word[j]- '0';
		}
	}

	//상하 좌우 
	int dy[4] = { -1,1,0,0 };
	int dx[4] = { 0,0,-1,1 };

	//bfs gogo
	queue<pair<pair<int, int>, int>>q;
	q.push({ {0,0}, 1 });
	

	while (!q.empty())
	{
		int curY = q.front().first.first;
		int curX = q.front().first.second;
		int value = q.front().second;

		q.pop();

		if (check[curY][curX])
			continue;
		check[curY][curX] = true;


		if (curY == n - 1 && curX == m - 1)
		{
			answer = value;
			break;
		}

		for (int i = 0; i < 4; i++)
		{
			int nY = curY + dy[i];
			int nX = curX + dx[i];

			if (nY < 0 || nY >= n
				|| nX < 0 || nX >= m)
				continue;

			if (v[nY][nX] != 1)
				continue;

			if (check[nY][nX])
				continue;

			q.push({ {nY, nX} , value + 1 });

		}


	}

	cout << answer;

	return 0;
}

profile
🔥🔥🔥

0개의 댓글

관련 채용 정보