C#/알고리즘

14. 4963번 섬의 개수

dev_sr 2020. 9. 5. 00:07

 

 

4963번: 섬의 개수

입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도�

www.acmicpc.net

 

2차원 배열을 써서 풀었음

배열에 값을 넣고 8방향으로 탐색하는 게 어려워서 검색해봤더니 그래프, DFS, BFS 문제라고 한다.

 

그래프는 연결되어 있는 객체 간의 관계를 표현할 수 있는 자료구조로 여려개의 고립된 부분 그래프로 구성될 수 있다.

트리와 다르게 루트, 노드의 개념이 없다.

일반적으로 DFS, BFS 로 탐색한다.

 

DFS(Depth First Search - 깊이 우선 방식)으로 Stack 구조나 재귀함수를 사용하여 구현

  -> 모든 노드 방문 (완벽 탐색)

 

BFS(Breadth First Search - 너비 우선 방식)으로 Queue 구조를 이용해서 구현

  -> 최단 경로, 임의의 경로를 찾을 때 사용

 

나는 재귀호출을 이용해서 구현했으니깐 DFS방식을 사용함????

어쨌거나 탐색은 제대로 했는데 답이 자꾸 큰 값이 나와서 이상했는데

결과값 도출하고 섬 갯수를 초기화를 안해서 누적된 거였음 

 

아무튼 맞긴 맞았는데 static이 너무 많다ㅋㅋ

나중에 정리해서 다시 풀어봐야겠다

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace _4963
{

    class Program
    {
        static int w;
        static int h;

        static int islandCount = 0;
        static int[] ax = { 0, 1, 1, 1, 0, -1, -1, -1 };
        static int[] ay = { 1, 1, 0, -1, -1, -1, 0, 1 };
        static int[,] map;
        static bool[,] visited;

        static void Main(string[] args)
        {
            while(true)
            {
                string[] input = Console.ReadLine().Split(' ');
                w = int.Parse(input[0]);
                h = int.Parse(input[1]);

                if (w == 0 && h == 0)
                {
                    break;
                }

                map = new int[h, w];
                visited = new bool[h, w];

                for (int i=0; i<h; i++)
                {
                    string[] landInput = Console.ReadLine().Split(' ');

                    for (int j=0; j<w; j++)
                    {
                        map[i, j] = int.Parse(landInput[j]);
                                               
                    }
                }

                for (int i = 0; i < h; i++)
                {
                    for (int j = 0; j < w; j++)
                    {    
                        if (!visited[i, j] && map[i, j] > 0)
                        {
                            ExamIsland(i, j);
                            islandCount++;
                        }

                    }
                }

                Console.WriteLine(islandCount);
                islandCount = 0;
                
            }

        }

        static void ExamIsland(int y, int x)
        {
            if(map[y,x]==0||visited[y,x])
            {
                return;
            }

            visited[y, x] = true;

            int dx = 0;
            int dy = 0;

            for(int i=0; i<8; i++)
            {
                dx = x + ax[i];
                dy = y + ay[i];

                if (dx>=0 && dx<w && dy>=0 && dy<h)
                {
                    ExamIsland(dy, dx);
                }
            }
        }
 
    }
}

 

그래프의 개념

 

[자료구조] 그래프(Graph)란 - Heee's Development Blog

Step by step goes a long way.

gmlwjd9405.github.io

DFS, BFS

 

[Algorithm] DFS와 BFS 기본과 예제 문제

Practice makes perfect!

twpower.github.io

참고한 코드

 

 

백준 4963번 섬의 개수

문제 링크입니다: https://www.acmicpc.net/problem/4963 DP에서 자주 나오던 간단한 그래프 이론 문제였기 때문에 쉽게 풀 수 있는 문제였습니다. 알고리즘은 다음과 같습니다. 1. 모든 그래프 좌표를 탐��

jaimemin.tistory.com

 

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

16. 2805번 나무 자르기  (0) 2020.09.06
15. 8980번 택배  (0) 2020.09.05
13. 1967번 트리의 지름  (0) 2020.07.26
12. 1074번 Z (시간 줄임)  (0) 2020.07.11
11. 2504번 괄호의 값 (해결)  (0) 2020.06.22