말이 복잡한데 코드로 보면 이해가 쉬울것이다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
using namespace std;
#define endl "\n"
#define MAX 1000+1
int m, n;
int board[MAX][MAX];
queue<pair<int, int>> q;
int dy[] = { 0,0,1,-1 };
int dx[] = { 1,-1,0,0 };
int cnt;
void bfs() {
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
if (board[i][j] == 1)
{
q.push({ i,j });
}
}
}
pair<int, int> firstNode = { 0,0 };
while (!q.empty())
{
pair<int, int> v = q.front();
if (v.first == firstNode.first && v.second==firstNode.second){
cnt++;
firstNode = { 0,0 };
}
q.pop();
for (int i = 0; i < 4; i++)
{
int nx = v.second + dx[i];
int ny = v.first + dy[i];
if (nx < 1 || nx > m || ny <1 || ny >n)
{
continue;
}
if (board[ny][nx] == 0)
{
board[ny][nx] = 1;
q.push({ ny,nx });
if (firstNode == make_pair(0, 0))
{
firstNode = { ny,nx };
}
}
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
//ifstream cin; cin.open("input.txt");
cin >> m >> n;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cin >> board[i][j];
}
}
bfs();
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
if (board[i][j] == 0) {
cnt = -1;
}
}
}
cout << cnt;
}
firstNode변수를 이용하지않고, board에 날짜를 기록해가면서 반복문을 이어가면 더 깔끔한 코드를 작성할 수 있다
void bfs() {
while (!q.empty())
{
pair<int, int> v = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int nx = v.second + dx[i];
int ny = v.first + dy[i];
if (nx < 1 || nx > m || ny <1 || ny >n)
{
continue;
}
if (board[ny][nx] == 0)
{
board[ny][nx] = board[v.first][v.second]+1; // 추가된 부분! 보드에 날짜를 기록
q.push({ ny,nx });
}
}
}
}
매일 자기전 연등시간에 2시간 시간내서 알고리즘 문제를 풀고있다.
2주 정도가 지났는데 확실히 실력이 늘은것이 보인다. 예전에 골드문제가 나오면 풀이방법도 안떠오르고, 머리에 있는걸 코드에 옮기기도 힘들었는데 향상된 부분이 눈에 보인다.
꾸준히해서 플래가자!
https://jdselectron.tistory.com/55 코드단축 및 디버깅 팁