[ 백준 26999 ] Satellite Photographs

2023. 2. 8. 10:26·Algorithm/문제풀이

1. 문제

 

26999번: Satellite Photographs

Farmer John purchased satellite photos of W x H pixels of his farm (1 ≤ W ≤ 80, 1 ≤ H ≤ 1000) and wishes to determine the largest 'contiguous' (connected) pasture. Pastures are contiguous when any pair of pixels in a pasture can be connected by tra

www.acmicpc.net

 

2. 풀이

해당 문제는 좌표계에서 BFS를 이용하여 Grouping 하는 기초를 다질 수 있는 문제다. 문제를 요약하자면 아스트리크(*) 로 연결된 가장 넓은 영역을 구하라는 것이다.

 

여기서 조건은 연결되었음을 판단하는 것은 '4 방위로 인접해있는가'다. 이를 풀이하기 위해서는 입력 받은 지도를 순차적으로 순회하면서 아스트리크('*')를 만났을 경우 BFS를 돌려 각 영역의 크기를 구해내면 된다. 당연하게도 방문했던 노드는 다시 방문해서는 안되며, 새로운 아스트리크를 만날 때마다 너비를 증가시키고 최종적으로 여러 구역의 크기 중 가장 큰 영역의 크기를 반환하면 해결!

 

3. 소스코드

더보기

 

public class Main {

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

    static int R, C;
    static char[][] map;
    static boolean[][] visit;

    static int solve() {
        int ret = 0;

        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                if (!visit[i][j] && map[i][j] == '*') {
                    ret = Math.max(ret, search(i, j));
                }
            }
        }

        return ret;
    }

    static int search(int y, int x) {
        Queue<Integer> q = new LinkedList<>();
        q.add(y * C + x);
        visit[y][x] = true;

        int cnt = 1;

        while (!q.isEmpty()) {
            int now = q.poll();
            int nowY = now / C;
            int nowX = now % C;

            for (int dir = 0; dir < 4; dir++) {
                int ny = nowY + dy[dir];
                int nx = nowX + dx[dir];
                if (!canVisit(ny, nx)) continue;
                q.add(ny * C + nx);
                visit[ny][nx] = true;
                cnt++;
            }
        }

        return cnt;
    }

    static boolean canVisit(int y, int x) {
        return 0 <= y && 0 <= x && y < R && x < C && !visit[y][x] && map[y][x] == '*';
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringTokenizer st = new StringTokenizer(br.readLine());
        C = Integer.parseInt(st.nextToken());
        R = Integer.parseInt(st.nextToken());

        map = new char[R][C];
        visit = new boolean[R][C];
        for (int i = 0; i < R; i++) {
            map[i] = br.readLine().toCharArray();
        }

        bw.write(solve() + "");
        bw.flush();
        bw.close();
        br.close();
    }
}
 

GitHub - kwanik-kor/BOJ: Baekjoon Online Judge - explanation of solved problems and complete code

Baekjoon Online Judge - explanation of solved problems and complete code - GitHub - kwanik-kor/BOJ: Baekjoon Online Judge - explanation of solved problems and complete code

github.com

 


BFS 개념은 아래 게시글을 참고♥️

 

그래프와 BFS(Graph & Breadth First Search)

BFS(너비 우선 탐색) 알고리즘에 대해 알아보기 전에 필수적으로 알아봐야 할 자료구조는 바로 그래프(Graph)다. 그래프는 실질적으로 프로그래밍 언어 라이브러리 상에서 제공하기 보다는 추상적

kwanik.tistory.com

 

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

'Algorithm > 문제풀이' 카테고리의 다른 글

[ 백준 16959 ] 체스판 여행 1  (0) 2023.02.09
[ 백준 1981 ] 배열에서 이동  (0) 2023.02.09
[ 백준 25416 ] 빠른 숫자 탐색  (0) 2023.02.07
[ 백준 2842 ] 집배원 한상덕  (0) 2020.07.27
[ 백준 2504 ] 괄호의 값 - Stack  (0) 2020.07.01
'Algorithm/문제풀이' 카테고리의 다른 글
  • [ 백준 16959 ] 체스판 여행 1
  • [ 백준 1981 ] 배열에서 이동
  • [ 백준 25416 ] 빠른 숫자 탐색
  • [ 백준 2842 ] 집배원 한상덕
갈닉
갈닉
중요한 건 엔지니어가 되겠다는 마음. 근데 이제 인문학을 곁들인.
    반응형
  • 갈닉
    KwanIk Devlog
    갈닉
  • 전체
    오늘
    어제
    • 분류 전체보기 (50)
      • Algorithm (39)
        • 알고리즘 개요 (8)
        • 문제풀이 (31)
      • Language (1)
        • Java (0)
        • Javascript (0)
        • Go (0)
        • Rust (1)
      • Framework (0)
        • Spring (0)
        • Spring Security (0)
        • Spring JPA (0)
      • Computer Science (1)
        • 프로그래밍 언어 (0)
        • 자료구조 (1)
        • 보안 (0)
      • DevOps (1)
        • MSA (0)
        • TDD (1)
        • DDD (0)
      • 개발서적 (3)
        • 오브젝트 (3)
      • Life (5)
        • 생각생각 (4)
        • 회고록 (1)
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

    • My Github
  • 공지사항

  • 인기 글

  • 태그

    DP
    욕심쟁이알고리즘
    Algorithm
    java
    BruteForce
    boj
    greedy
    backtracking
    깊이우선탐색
    백준
    비트마스크
    bitmask
    너비우선탐색
    알고리즘
    오브젝트
    BFS
    객체지향
    백트래킹
    구현
    시뮬레이션
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
갈닉
[ 백준 26999 ] Satellite Photographs
상단으로

티스토리툴바