https://www.acmicpc.net/problem/4963
4963번: 섬의 개수
문제 정사각형으로 이루어져 있는 섬과 바다 지도가 주어진다. 섬의 개수를 세는 프로그램을 작성하시오. 한 정사각형과 가로, 세로 또는 대각선으로 연결되어 있는 사각형은 걸어갈 수 있는 사각형이다. 두 정사각형이 같은 섬에 있으려면, 한 정사각형에서 다른 정사각형으로 걸어서 갈 수 있는 경로가 있어야 한다. 지도는 바다로 둘러쌓여 있으며, 지도 밖으로 나갈 수 없다. 입력 입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는
www.acmicpc.net
단순한 완전탐색 문제이다.
다만 visit을 사용하기 싫어서 탐색한 map의 값을 0으로 바꿔준 것이 특징이다.
<JAVA>
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
class Pos {
Pos(int x, int y) {
this.x = x;
this.y = y;
}
int x, y;
}
class Main {
static int dx[] = { 1, -1, 0, 0, -1, -1, 1, 1 };
static int dy[] = { 0, 0, 1, -1, -1, 1, -1, 1 };
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int w, h, cnt, x, y;
while (true) {
cnt = 0;
st = new StringTokenizer(br.readLine(), " ");
h = Integer.parseInt(st.nextToken(" "));
w = Integer.parseInt(st.nextToken(" "));
if (w == 0 && h == 0)
break;
int map[][] = new int[w][h];
for (int i = 0; i < w; ++i) {
st = new StringTokenizer(br.readLine(), " ");
for (int j = 0; j < h; ++j) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
for (int i = 0; i < w; ++i) {
for (int j = 0; j < h; ++j) {
{
if (map[i][j] == 1) {
++cnt;
Queue<Pos> q = new LinkedList<>();
q.add(new Pos(i, j));
map[i][j] = 0;
while (!q.isEmpty()) {
Pos cur = q.poll();
for (int dir = 0; dir < 8; ++dir) {
int nx = cur.x + dx[dir];
int ny = cur.y + dy[dir];
if (nx >= w || ny >= h || nx < 0 || ny < 0 || map[nx][ny] == 0) {
continue;
}
q.add(new Pos(nx, ny));
map[nx][ny] = 0;
}
}
}
}
}
}
System.out.println(cnt);
}
}
}
<C++>
#include<iostream>
#include<queue>
using namespace std;
struct Pos {
int x, y;
};
int dx[] = { 1, -1, 0, 0, -1, -1, 1, 1 };
int dy[] = { 0, 0, 1, -1, -1, 1, -1, 1 };
int map[50][50];
int main()
{
cin.tie(NULL); cout.tie(NULL); ios_base::sync_with_stdio(false);
int w, h, cnt, x, y;
Pos p;
while (true) {
cnt = 0;
cin >> h >> w;
if (w == 0 && h == 0)
break;
for (int i = 0; i < w; ++i) {
for (int j = 0; j < h; ++j) {
cin >> map[i][j];
}
}
for (int i = 0; i < w; ++i) {
for (int j = 0; j < h; ++j) {
{
if (map[i][j] == 1) {
++cnt;
queue<Pos> q;
p.x = i;
p.y = j;
q.push(p);
map[i][j] = 0;
while (!q.empty()) {
Pos cur = q.front();
q.pop();
for (int dir = 0; dir < 8; ++dir) {
int nx = cur.x + dx[dir];
int ny = cur.y + dy[dir];
if (nx >= w || ny >= h || nx < 0 || ny < 0 || map[nx][ny] == 0) {
continue;
}
p.x = nx;
p.y = ny;
q.push(p);
map[nx][ny] = 0;
}
}
}
}
}
}
cout << cnt<<"\n";
}
}
'알고리즘 > BOJ' 카테고리의 다른 글
14889. 스타트와 링크 (0) | 2019.10.15 |
---|---|
16235. 나무재테크 (0) | 2019.10.15 |
13460. 구슬 탈출 2 (0) | 2019.10.15 |
1717. 집합의 표현 (0) | 2019.10.14 |
1157. 단어 공부 (0) | 2019.10.08 |