• Home
  • About
    • Ryureka Moment photo

      Ryureka

      Sin Prisa, Sin Pausa

    • About Me
    • Facebook
    • Github
    • Youtube
  • Projects
  • Posts
    • Posts
    • ProblemSolvings
    • Tags
    • Blog
    • Examples
  • ProblemSolving
    • ProblemSolving
    • BOJ
    • Programmers
    • SWEA
    • LeetCode
  • FrontEnd
    • FrontEnd
    • HTML
  • BackEnd
    • BackEnd
    • Server
      • Server
      • Spring
      • NodeJS
    • DataBase
      • DataBase
      • MySQL
      • MongoDB
  • Programming
    • Programming
    • Java
    • JS
    • Python
    • CleanCode
  • ComputerScience
    • DataStructure
    • Algorithm

[BOJ] 1926. 그림

15 Apr 2026

Reading time ~1 minute

  • 풀이

풀이

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
	static int N,M;
	static int[][] map;
	static boolean[][] check;
	static int[][] dist;
	static int[] dx = {0,1,0,-1};
	static int[] dy = {1,0,-1,0};
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		M = sc.nextInt();
		map = new int [N][M];
		check = new boolean[N][M];
		dist = new int [N][M];
		
		for(int i = 0; i < N; i++) {
			for(int j = 0; j < M; j++) {
				map[i][j] = sc.nextInt();				
			}
		}
		
				
		for(int i = 0; i < N; i++) {
			for(int j = 0; j < M; j++) {
				if(!check[i][j] && map[i][j] == 1) {
					bfs(new Point(j,i));
				}
			}
		}
		
		int ans1 = 0;
		int ans2 = 0;
		for(int i = 0; i < N; i++) {
			for(int j = 0; j < M; j++) {
				if(dist[i][j] == 1) ans1++;
			}
		}
		
		for(int i = 0; i < N; i++) {
			for(int j = 0; j < M; j++) {
				if(ans2 < dist[i][j]) ans2 = dist[i][j];
			}
		}
		
		System.out.println(ans1);
		System.out.println(ans2);
		
	}
	
	static void bfs(Point p) {
		Queue<Point> q = new LinkedList<>();
		q.add(p); 
		check[p.y][p.x] = true;
		int cnt = 0; 
		cnt++;
		dist[p.y][p.x] = cnt;		
		while(!q.isEmpty()) {
			Point c = q.poll();
			for(int i = 0; i < dx.length; i++) {
				int nx = c.x + dx[i];
				int ny = c.y + dy[i];
				if(nx < 0 || nx >= M || ny < 0 || ny >= N) continue;
				if(!check[ny][nx] && map[ny][nx] == 1) {
					q.add(new Point(nx,ny));
					check[ny][nx] = true;
					cnt++;
					dist[ny][nx] = cnt;
				}				
			}
		}
	}
	
	static class Point{
		int x,y;
		Point(int x, int y) {
			this.x = x;
			this.y = y;
		}
	}
}


BFSDFS플러드 필 Share