[C#] 백준 2667번 단지번호붙이기 (DFS, BFS)

2024. 5. 25. 21:07·Language/C#
반응형

[ 문제 ]

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.

 

[ 코드 ]

1. DFS

class Program
{
    static int n;
    static int[,] graph;
    static List<int> num = new List<int>(); // 각 연결된 단지의 크기를 저장할 리스트
    static int[] dx = { 0, 0, 1, -1 };
    static int[] dy = { 1, -1, 0, 0 };
    static int count = 0; // 현재 단지의 집 개수

    static bool DFS(int x, int y)
    {
        if (x < 0 || x >= n || y < 0 || y >= n)
        {
            return false;
        }
        
        if (graph[x, y] == 1) // 현재 위치에 집이 있으면
        {
            count += 1;
            graph[x, y] = 0;
            for (int i = 0; i < 4; i++) // 네 방향으로 이동
            {
                int nx = x + dx[i];
                int ny = y + dy[i];
                DFS(nx, ny);
            }
            return true;
        }
        return false; 
    }

    static void Main(string[] args)
    {
        StreamReader sr = new StreamReader(Console.OpenStandardInput());
        StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());

        n = int.Parse(sr.ReadLine());
        graph = new int[n, n];

        for (int i = 0; i < n; i++)
        {
            string input = sr.ReadLine();
            for (int j = 0; j < n; j++)
            {
                graph[i, j] = input[j] - '0';
            }
        }

        int result = 0;	// 단지 수

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (DFS(i, j))
                {
                    num.Add(count);
                    result += 1;
                    count = 0;
                }
            }
        }

        num.Sort();
        sw.WriteLine(result);
        foreach (int number in num)
        {
            sw.WriteLine(number);
        }

        sw.Flush();
        sw.Close();
        sr.Close();
    }
}

 

2. BFS

- C#에는 덱이 없어서 LinkedList를 이용해서 양쪽에서 추가하고 제거할 수 있게함

class Program
{
    static int[] dx = { 0, 0, 1, -1 };
    static int[] dy = { 1, -1, 0, 0 };

    static int BFS(int[,] graph, int a, int b)
    {
        int n = graph.GetLength(0);
        LinkedList<Tuple<int, int>> group = new LinkedList<Tuple<int, int>>();
        group.AddLast(new Tuple<int, int>(a, b));
        graph[a, b] = 0;
        int count = 1;

        while (group.Count > 0)
        {
            var node = group.First; // 큐 첫 번째 노드
            var (x, y) = node.Value; // 현재 위치 좌표
            group.RemoveFirst(); // 큐에서 제거
            
            for (int i = 0; i < 4; i++)
            {
                int nx = x + dx[i];
                int ny = y + dy[i];
                if (nx < 0 || nx >= n || ny < 0 || ny >= n)
                {
                    continue;
                }
                if (graph[nx, ny] == 1)
                {
                    graph[nx, ny] = 0;
                    group.AddLast(new Tuple<int, int>(nx, ny)); // 큐에 추가
                    count += 1;
                }
            }
        }
        return count;
    }

    static void Main(string[] args)
    {
        StreamReader sr = new StreamReader(Console.OpenStandardInput());
        StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());

        int n = int.Parse(sr.ReadLine());
        int[,] graph = new int[n, n];

        for (int i = 0; i < n; i++)
        {
            string input = sr.ReadLine();
            for (int j = 0; j < n; j++)
            {
                graph[i, j] = input[j] - '0';
            }
        }

        List<int> cnt = new List<int>();
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (graph[i, j] == 1)
                {
                    cnt.Add(BFS(graph, i, j));
                }
            }
        }

        cnt.Sort();
        sw.WriteLine(cnt.Count);
        foreach (int count in cnt)
        {
            sw.WriteLine(count);
        }

        sw.Flush();
        sw.Close();
        sr.Close();
    }
}

 

[ 실행화면 ]

case: 1

 

 

 


문제링크: https://www.acmicpc.net/problem/2667

 

반응형
저작자표시 비영리 변경금지 (새창열림)

'Language > C#' 카테고리의 다른 글

[C#] 백준 21964번 선린인터넷고등학교 교가 (문자열 자르는 Substring 함수)  (2) 2024.06.01
[C#] 백준 2178번 미로 탐색  (0) 2024.05.31
[C#] 백준 1188번 음식 평론가 (유클리드 호제법)  (1) 2024.05.19
[C#] 백준 9372번 상근이의 여행 (DFS 활용)  (0) 2024.05.14
[C#] 백준 24060번 알고리즘 수업 - 병합 정렬 1  (0) 2024.05.08
'Language/C#' 카테고리의 다른 글
  • [C#] 백준 21964번 선린인터넷고등학교 교가 (문자열 자르는 Substring 함수)
  • [C#] 백준 2178번 미로 탐색
  • [C#] 백준 1188번 음식 평론가 (유클리드 호제법)
  • [C#] 백준 9372번 상근이의 여행 (DFS 활용)
석영
석영
관심 분야는 AR, VR, 게임이고 유니티 공부 중 입니다. (정보처리기사,컴퓨터그래픽스운용기능사 취득)
유석영의 개발공부관심 분야는 AR, VR, 게임이고 유니티 공부 중 입니다. (정보처리기사,컴퓨터그래픽스운용기능사 취득)
반응형
석영
유석영의 개발공부
석영
전체
오늘
어제
  • 분류 전체보기
    • Unity
      • Project
      • Tip
      • Assets
    • Record
      • TIL
      • Game
    • Language
      • C#
      • Node.js
      • HTML, JS
    • Study
      • Linear Algebra

인기 글

최근 글

hELLO· Designed By정상우.v4.5.2
석영
[C#] 백준 2667번 단지번호붙이기 (DFS, BFS)

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.