초기 네이버 기록/알고리즘(C)

백준 토마토 성공!! 1068번 BFS(C언어)

뜨거운 개발자 2023. 1. 4. 00:03
#include<stdio.h>
int map[1001][1001] = { -1 };
int cue[1100000] = { 0 };

void bfs(int length,int width)
{
	
	int count = 0;
	int front = 0;
	int rear = 0;
	int pop;
	for (int i = 0; i < length; i++)
	{
		for (int j = 0; j < width; j++)
		{
			if (map[i][j] == 1)
				cue[rear++] = i * width + j;
		}
	}
	int first = rear;
	while (front <= rear)
	{
		pop = cue[front++];
		int y = pop / width;
		int x = pop % width;
		if (y + 1 < length && map[y + 1][x] == 0)
		{
			cue[rear++]=pop + width;
			map[y + 1][x] = map[y][x]+1;
		}
		if (0 < y && map[y - 1][x] == 0)
		{
			cue[rear++] = pop - width;
			map[y - 1][x] = map[y][x] + 1;
		}
		if (x + 1 < width && map[y ][x+1] == 0)
		{
			cue[rear++] = pop+1;
			map[y][x+1] = map[y][x] + 1;
		}
		if (0 < x && map[y][x-1] == 0)
		{
			cue[rear++] = pop -1;
			map[y ][x-1] = map[y][x] + 1;
		}
	}
}

int main()
{
	int width, length;
	
	scanf("%d %d", &width, &length);
	int tomato = 0;
	for (int i = 0; i < length; i++)
	{
		for (int j = 0; j < width; j++)
		{
			scanf("%d", &map[i][j]);
			if (map[i][j] == 1)
				tomato = 1;
		}
	}

	bfs(length,width);
	int max = 0;
	int check = 0;
	for (int i = 0; i < length; i++)
	{
		for (int j = 0; j < width; j++)
		{
			//printf("%d ", map[i][j]);
			if (map[i][j] > max)
				max = map[i][j];
			if (map[i][j] == 0)
				check = 1;
		}
		//printf("\n");
	}
	//printf("check: %d tomato:%d\n", check, tomato);
	if (check || tomato == 0)
		printf("-1");
	else if (max == 0)
		printf("0");
	else
		printf("%d", max-1);
}

오래 걸렸지만 스스로 해내서 정말 기뻤다.

스스로 bfs를 구현했다는 것이 기분이 참 좋았다.

728x90