본문 바로가기
이론/코딩테스트

[백준] 1388번 바닥 장식 (BFS)

by 퇴근후개발 2022. 8. 26.
반응형

- 문제

 

-코드

#include<queue>
#include<iostream>

using namespace std;

int d[2] = {1,-1};

int main()
{
	int n, m, cnt=0;
	cin >> n >> m;

	char map[50][50];
	char ch[50][50];

	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			cin >> map[i][j];
		}
	}

	queue<pair<int,int> > q;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			if (map[i][j] == '-')
			{
				q.push({i,j});
				map[i][j] = '0';
				while (!q.empty())
				{
					pair<int, int> tmp = q.front();
					q.pop();
					for (int k = 0; k < 2; k++)
					{
						int yy =  tmp.second + d[k];
						if (yy >= m || yy < 0) continue;
						if (map[i][yy] == '-')
						{
							q.push({i,yy});
							map[i][yy] = '0';
						}	
					}
				}
				cnt++;
			}

			if (map[i][j] == '|')
			{
				q.push({ i,j });
				map[i][j] = '0';
				while (!q.empty())
				{
					pair<int, int> tmp = q.front();
					q.pop();
					for (int k = 0; k < 2; k++)
					{
						int xx = tmp.first + d[k];
						if (xx >= n || xx < 0) continue;
						if (map[xx][j] == '|')
						{
							q.push({ xx,j });
							map[xx][j] = '0';
						}
					}
				}
				cnt++;
			}
			/*
			cout << "--------------------------\n";
			for (int x = 0; x < n; x++)
			{
				for (int y = 0; y < m; y++)
				{
					cout << map[x][y];
				}
				cout << '\n';
			}
			*/
		}
	}

	cout << cnt;

	return 0;
}
반응형