[백준] 21938 - 영상처리
1. 문제
2. 개요
R, G, B의 3요소로 이루어진 N x M개의 픽셀로 구성된 N x M 크기의 화면이 있다.
픽셀에서 3개의 요소의 값을 평균으로 하여 K 이상이라면 값을 255, 아니라면 0으로 저장한다.
필셀값이 255라면 하나의 물체로 간주하며, 값이 255인 픽셀이 상하좌우로 인접해 있다면 같은 물체로 취급한다.
각 픽셀의 R, G, B값이 주어졌을 때, 화면 내의 물체의 총 개수를 구하는 문제.
3. 풀이 및 코드
3-1. 풀이
주어진 픽셀의 R, G, B값들을 먼저 N x M 크기의 픽셀의 값으로 변환한다.
이후 DFS를 진행하며 물체의 총 개수를 찾아낸 후 답을 출력한다.
3-2. Python
import sys
sys.setrecursionlimit(1000000)
N, M = map(int, sys.stdin.readline().split())
pixels = []
board = []
for i in range(N):
pixels.append(list(map(int, sys.stdin.readline().split())))
T = int(sys.stdin.readline())
for i in range(N):
board.append([])
for j in range(0, M * 3, 3):
if (pixels[i][j] + pixels[i][j+1] + pixels[i][j+2]) / 3 >= T:
board[i].append(1)
else:
board[i].append(0)
visited = [[False for i in range(M)] for j in range(N)]
def DFS(y, x):
dirY, dirX = [-1, 0, 1, 0], [0, -1, 0, 1]
for i in range(4):
nextY, nextX = y + dirY[i], x + dirX[i]
if nextY < 0 or nextY >= N or nextX < 0 or nextX >= M:
continue
if visited[nextY][nextX] == True:
continue
if board[nextY][nextX] != 1:
continue
visited[nextY][nextX] = True
DFS(nextY, nextX)
answer = 0
for i in range(N):
for j in range(M):
if visited[i][j] == False and board[i][j] == 1:
visited[i][j] = True
DFS(i,j)
answer += 1
print(answer)
3-3. C#
namespace boj_21938
{
internal class Program
{
static int N;
static int M;
static int[,] board;
static bool[,] visited;
static void Main(string[] args)
{
StreamReader sr = new StreamReader(Console.OpenStandardInput());
StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
string[] input = sr.ReadLine().Split();
N = int.Parse(input[0]); M = int.Parse(input[1]);
int[,] pixels = new int[N, M * 3];
board = new int[N, M];
for (int i = 0; i < N; i++)
{
string[] info = sr.ReadLine().Split();
for (int j = 0; j < M * 3; j++)
{
pixels[i, j] = int.Parse(info[j]);
}
}
int T = int.Parse(sr.ReadLine());
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M * 3; j += 3)
{
if ((pixels[i, j] + pixels[i, j + 1] + pixels[i, j + 2]) / 3 >= T)
{
board[i, j / 3] = 1;
}
else
{
board[i, j / 3] = 0;
}
}
}
visited = new bool[N, M];
int answer = 0;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
if (board[i, j] == 1 && !visited[i, j])
{
visited[i, j] = true;
DFS(i, j);
answer++;
}
}
}
sw.WriteLine(answer);
sw.Close();
}
static void DFS (int y, int x)
{
int[] dirY = { -1, 0, 1, 0 };
int[] dirX = { 0, -1, 0, 1 };
for (int i = 0; i < 4; i++)
{
int nextY = y + dirY[i];
int nextX = x + dirX[i];
if (nextY < 0 || nextY >= N || nextX < 0 || nextX >= M)
continue;
if (board[nextY, nextX] != 1)
continue;
if (visited[nextY, nextX] == true)
continue;
visited[nextY, nextX] = true;
DFS(nextY, nextX);
}
}
}
}
Comments