티스토리 뷰
728x90
문제
https://www.acmicpc.net/problem/4963
4963번: 섬의 개수
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도
www.acmicpc.net
풀이 및 소스코드
대각선까지므로 dx, dy를 9방향으로 만들어 준 후,
섬을 만나면 bfs로 방문처리를 해주었다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int[] p;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
StringBuilder sb = new StringBuilder();
while (true) {
st = new StringTokenizer(br.readLine());
int w = Integer.parseInt(st.nextToken());
// w : 너비
int h = Integer.parseInt(st.nextToken());
// h : 높이
if(w==0&&h==0) break;
int[][] map = new int[h][w];
for (int i = 0; i < h; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < w; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
Queue<node> q = new LinkedList<node>();
int[] dx = { -1, -1, -1, 0, 0, 0, 1, 1, 1 };
int[] dy = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
int res = 0;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (map[i][j] == 0)
continue;
q.add(new node(i, j));
map[i][j] = 0;
res++;
while(!q.isEmpty()) {
node xy = q.poll();
for(int k=0;k<9;k++) {
int nowx = xy.x+dx[k];
int nowy = xy.y+dy[k];
if(0>nowx||0>nowy||h<=nowx||w<=nowy) continue;
if(map[nowx][nowy]!=0) {
q.add(new node(nowx, nowy));
map[nowx][nowy] = 0;
}
}
}
}
}
sb.append(res).append("\n");
}
System.out.println(sb);
}
}
class node {
int x, y;
public node(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
반응형
'Coding - Algo > Java' 카테고리의 다른 글
[백준] 14499번:주사위 굴리기 (Java 자바) (0) | 2021.11.04 |
---|---|
[백준] 13335번:트럭 (Java 자바) (0) | 2021.11.01 |
[백준] 14889번:스타트와 링크 (Java 자바) (0) | 2021.10.26 |
[백준] 21608번:상어 초등학교 (Java 자바) (0) | 2021.10.19 |
[백준] 18352번:특정 거리의 도시 찾기 (Java 자바) (0) | 2021.10.19 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 백준 17144
- 백준파이썬
- 삼성청년SW아카데미
- 1699 자바
- swea 4070 타일링
- swea 타일링
- 우분투
- 백준 풀이
- swea 타일링 자바
- 타일링 자바
- 3996 자바
- swea 1240 자바
- yoloV3
- 더 맵게
- poker swea
- 프로그래머스 자바
- 프로그래머스
- union-find
- 백준 dp 문제
- 파이썬 풀이
- swea 1240
- 파이썬
- 프로그래머스 더 맵게
- SWEA
- 메뉴리뉴얼 풀이
- 프로그래머스 파이썬
- 1240 자바
- SSAFY
- ubuntu
- 백준
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함