-
[java] 백준 4963 섬의 개수알고리즘 2023. 6. 9. 00:35
https://www.acmicpc.net/problem/4963
4963번: 섬의 개수
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도
www.acmicpc.net
import java.io.*; import java.util.*; public class Main { static int arr[][]; static boolean visited[][]; static int dx[] = {0,0,-1,1,-1,1,-1,1}; static int dy[] = {-1,1,0,0,1,1,-1,-1}; static int w,h,nx,ny; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; String str = " "; while( !(str = br.readLine()).equals("0 0")) { st = new StringTokenizer(str); w = Integer.parseInt(st.nextToken()); h = Integer.parseInt(st.nextToken()); arr = new int[h][w]; visited = new boolean[h][w]; for(int i=0; i<h; i++) { st = new StringTokenizer(br.readLine()); for(int j=0; j<w; j++) { arr[i][j] = Integer.parseInt(st.nextToken()); } } int cnt =0; for(int i=0; i<h; i++) { for(int j=0; j<w; j++) { if(!visited[i][j] && arr[i][j]==1) { cnt++; DFS(i,j); } } } System.out.println(cnt); } } static void DFS(int x,int y) { visited[x][y] = true; for(int i=0; i<8; i++) { nx = dx[i]+x; ny = dy[i]+y; if(nx>=0 && ny>=0 &&nx<h && ny<w) { if(!visited[nx][ny] && arr[nx][ny]==1) { DFS(nx,ny); } } } } }
'알고리즘' 카테고리의 다른 글
<문자열> 프로그래머스 문자열 내 마음대로 정렬하기 java (0) 2023.06.18 [java] 백준 좌표정렬하기2 (0) 2023.06.09 <이분탐색> 백준 2512 예산 (0) 2023.05.30 <dp> 프로그래머스 멀리 뛰기 (0) 2023.05.27 <문자열> 프로그래머스 lv.1 숫자 문자열과 영단어 (0) 2023.05.27