티스토리 뷰

반응형

https://softeer.ai/practice/info.do?idx=1&eid=409 

 

Softeer

연습문제를 담을 Set을 선택해주세요. 취소 확인

softeer.ai

[문제]

자율주행팀 SW 엔지니어인 당신에게 장애물과 도로를 인식할 수 있는 프로그램을 만들라는 업무가 주어졌다.

 

[그림 1] 지도 예시

 

우선 [그림 1]과 같이 정사각형 모양의 지도가 있다. 1은 장애물이 있는 곳을, 0은 도로가 있는 곳을 나타낸다.

 

당신은 이 지도를 가지고 연결된 장애물들의 모임인 블록을 정의하고, 불록에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 장애물이 좌우, 혹은 아래위로 붙어 있는 경우를 말한다. 대각선 상에 장애물이 있는 경우는 연결된 것이 아니다.

 

 

[그림 2] 블록 별 번호 부여

 

[그림 2]는 [그림 1]을 블록 별로 번호를 붙인 것이다. 

 

지도를 입력하여 장애물 블록수를 출력하고, 각 블록에 속하는 장애물의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.

 

[풀이]

import java.util.*;
import java.io.*;


class Location
{
	int row, col;
	
	public Location(int nRow, int nCol)
	{
		row = nRow;
		col = nCol;
	}
}

public class Main
{
    
	static int N; // 5<= N <= 25
	static int MAP[][];
	static boolean VISITED[][];
	static ArrayList<Integer> BLOCK;
	static Queue<Location> queue = new LinkedList<>();
	
	static int[] DX = { -1, 0, 1, 0 };
	static int[] DY = { 0, 1, 0, -1 };
	
	public static void main(String[] args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		N = Integer.parseInt(br.readLine());
		
		MAP = new int[N][N];
		VISITED = new boolean[N][N];
		
		for (int i = 0; i < N; i++)
		{
			String strMap = br.readLine();
			for (int j = 0; j < N; j++)
			{
				MAP[i][j] = strMap.charAt(j) - '0';
				VISITED[i][j] = false;
			}
		}
		
		BLOCK = new ArrayList<>();
		
		for (int i = 0; i < N; i++)
		{
			for (int j = 0; j < N; j++)
			{
				if (MAP[i][j] == 1 && !VISITED[i][j])
				{
					VISITED[i][j] = true;
					queue.add(new Location(i, j));
					BFS();
				}
			}
		}
		
		System.out.println(BLOCK.size());
		Collections.sort(BLOCK);
		for (int i = 0; i < BLOCK.size(); i++)
		{
			System.out.println(BLOCK.get(i));
		}
		
		br.close();
	}
	
	private static void BFS()
	{
		int nCount = 1;
		while (!queue.isEmpty())
		{
			// 큐에서 노드를 poll
			Location location = queue.poll();
			int row = location.row;
			int col = location.col;
			
			// 상하좌우 4방향 노드에 대한 작업
			for (int i = 0; i < 4; i++)
			{
				int x = row + DX[i];
				int y = col + DY[i];
				
				if (x < 0 || x >= N || y < 0 || y >= N)
					continue;
				
				if (MAP[x][y] != 1 || VISITED[x][y])
					continue;
				
				// 큐에 인접 노드 추가
				queue.add(new Location(x, y));
				VISITED[x][y] = true;
				nCount++;
			}
		}
		BLOCK.add(nCount);
	}

}
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함