DFS
import java.util.Scanner;
public class Main{
static int n, answer=0;
static int[] dx = {-1, -1, 0, 1, 1, 1, 0, -1};
static int[] dy = {0, 1, 1, 1, 0, -1, -1, -1};
public void DFS(int x, int y, int[][] board){
for(int i=0; i<8; i++){
int nx=x+dx[i];
int ny=y+dy[i];
if(nx>=0 && nx<n && ny>=0 && ny<n && board[nx][ny]==1){ // 섬이라면
board[nx][ny]=0; // 바다로 바꿈
DFS(nx, ny, board);
}
}
}
public void solution(int[][] board){
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(board[i][j]==1){
answer++;
board[i][j]=0; // 첫 시작점 바다로 바꿈
DFS(i, j, board);
}
}
}
}
public static void main(String[] args) {
Main T = new Main();
Scanner kb = new Scanner(System.in);
n = kb.nextInt();
int[][] arr = new int[n][n];
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
arr[i][j]=kb.nextInt();
}
}
T.solution(arr);
System.out.println(answer);
}
}
BFS
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Point{
int x, y;
Point(int x, int y){
this.x=x;
this.y=y;
}
}
public class Main{
static int n, answer=0;
static int[] dx = {-1, -1, 0, 1, 1, 1, 0, -1};
static int[] dy = {0, 1, 1, 1, 0, -1, -1, -1};
Queue<Point> queue = new LinkedList<>();
public void BFS(int x, int y, int[][] board){
queue.add(new Point(x,y));
while(!queue.isEmpty()){
Point pos = queue.poll();
for(int i=0; i<8; i++){
int nx=pos.x+dx[i];
int ny=pos.y+dy[i];
if(nx>=0 && nx<n &&ny>=0 &&ny<n && board[nx][ny]==1){
board[nx][ny]=0;
queue.add(new Point(nx, ny));
}
}
}
}
public void solution(int[][] board){
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(board[i][j]==1){
answer++;
board[i][j]=0;
BFS(i,j,board);
}
}
}
}
public static void main(String[] args) {
Main T = new Main();
Scanner kb = new Scanner(System.in);
n = kb.nextInt();
int[][] arr = new int[n][n];
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
arr[i][j]=kb.nextInt();
}
}
T.solution(arr);
System.out.println(answer);
}
}
'ALGORITHM' 카테고리의 다른 글
[JAVA] 백준 2607번- 비슷한 단어 (0) | 2022.10.02 |
---|---|
[JAVA] 알고리즘 : DFS- 피자 배달 거리 (0) | 2022.09.30 |
[JAVA] 알고리즘 : DFS- 미로 탐색 (0) | 2022.09.29 |
[JAVA] 백준 10814번- 나이순 정렬 (0) | 2022.09.29 |
[JAVA] 백준 1181번 - 단어 정렬 (0) | 2022.09.28 |