Flood Fill Algorithm

2023. 4. 14. 12:22·📚 Data Architect/Algorithm
목차
  1. 💡 Flood Fill 알고리즘
  2. DFS & Stack을 이용한 Flood Fill 구현

💡 Flood Fill 알고리즘

다차원 배열의 어떤 칸과 연결된 영약을 찾는 알고리즘이다.

바둑이나 지뢰찾기 같은 게임에서 어떤 비어 있는 칸을 표시할 지 를 결정할 때도 사용된다.

DFS와 Stack을 이용하여 구현하기도 하고, BFS와 Queue를 이용해 구현하기도 한다.


DFS & Stack을 이용한 Flood Fill 구현

import java.util.Scanner;
import java.util.Stack;

public class DFS_FloodFill {
    // 상하좌우를 의미하는 델타 배열 생성
    static int[][] deltaArray = {{-1,0}, {1,0}, {0,-1}, {0,1}};
    static final int max = 10;
    static int n;
    static int[][] graph = new int[max][max];

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();

        for (int i=0; i<n; ++i) {
            for (int j=0; j<n; ++n) {
                graph[i][j] = sc.nextInt();
            }
        }

        int sRow = sc.nextInt();
        int sCol = sc.nextInt();
        int color = sc.nextInt();

        dfs(sRow,sCol,color);

        for (int i=0; i<n; ++i) {
            for (int j=0; j<n; ++j) {
                System.out.println(graph[i][j] + " ");
            }
            System.out.println();
        }
    }

    // DFS 알고리즘
    public static void dfs(int r, int c, int color) {
        boolean[][] flag = new boolean[n][n];
        Stack<Point> stack = new Stack<>();
        stack.push(new Point(r,c));

        while (!stack.empty()) {
            Point cur = stack.pop();
            if (flag[cur.row][cur.col]) continue;

            flag[cur.row][cur.col] = true;
            graph[cur.row][cur.col] = color;

            for (int i=0; i<4; ++i) {
                int nr = cur.row + deltaArray[i][0];
                int nc = cur.col + deltaArray[i][1];

                if (flag[nr][nc]) continue;
                if (graph[nr][nc] == 1) continue;
                stack.push(new Point(nr, nc));
            }
        }
    }

    // 행 & 열 좌표 클래스
    public static class Point {
        int row;
        int col;
        Point(int r, int c) {
            row = r;
            col = c;
        }
    }
}
저작자표시 (새창열림)

'📚 Data Architect > Algorithm' 카테고리의 다른 글

Dynamic Programming (동적 계획법)  (0) 2023.04.14
Quick Sort  (0) 2023.04.14
Insertion Sort  (0) 2023.04.14
Selection Sort  (0) 2023.04.14
Bubble Sort  (0) 2023.04.13
  1. 💡 Flood Fill 알고리즘
  2. DFS & Stack을 이용한 Flood Fill 구현
'📚 Data Architect/Algorithm' 카테고리의 다른 글
  • Dynamic Programming (동적 계획법)
  • Quick Sort
  • Insertion Sort
  • Selection Sort
신건우
신건우
조용한 개발자
  • 신건우
    우주먼지
    신건우
  • 전체
    오늘
    어제
    • 분류 전체보기 (422)
      • 📘 Frontend (71)
        • Markup (1)
        • Style Sheet (2)
        • Dart (8)
        • Javascript (12)
        • TypeScript (1)
        • Vue (36)
        • React (2)
        • Flutter (9)
      • 📘 Backend (143)
        • Java (34)
        • Concurrency (19)
        • Reflection (1)
        • Kotlin (29)
        • Python (1)
        • Spring (42)
        • Spring Cloud (5)
        • Message Broker (5)
        • Streaming (2)
        • 기능 개발 (5)
      • 💻 Server (6)
        • Linux (6)
      • ❌ Error Handling (11)
      • 📦 Database (62)
        • SQL (31)
        • NoSQL (2)
        • JPQL (9)
        • QueryDSL (12)
        • Basic (4)
        • Firebase (4)
      • ⚙️ Ops (57)
        • CS (6)
        • AWS (9)
        • Docker (8)
        • Kubernetes (13)
        • MSA (1)
        • CI & CD (20)
      • 📚 Data Architect (48)
        • Data Structure (10)
        • Algorithm (8)
        • Programmers (17)
        • BaekJoon (5)
        • CodeUp (4)
        • Design Pattern (4)
        • AI (0)
      • ⚒️ Management & Tool (8)
        • Git (7)
        • IntelliJ (1)
      • 📄 Document (10)
        • Project 설계 (6)
        • Server Migration (3)
      • 📄 책읽기 (2)
        • 시작하세요! 도커 & 쿠버네티스 (2)
      • 🎮 Game (4)
        • Stardew Vally (1)
        • Path of Exile (3)
  • 블로그 메뉴

    • 링크

      • Github
    • 공지사항

    • 인기 글

    • 태그

      GStreamer #Pipeline
      Lock #Thread #Concurrency
      React #Markdown
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.0
    신건우
    Flood Fill Algorithm
    상단으로

    티스토리툴바

    단축키

    내 블로그

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

    블로그 게시글

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

    모든 영역

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

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