๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 27211_๋„๋„› ํ–‰์„ฑ

๋ฟŒ์•ผ._. 2023. 5. 21. 23:32

Gold V

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/27211)

< ๋„๋„› ํ–‰์„ฑ>

 

๋ฌธ์ œ ํ’€์ด

 

๋น„์–ด์žˆ๋Š” ๊ณณ์—์„œ ์ƒํ•˜์ขŒ์šฐ๋ฅผ ํƒ์ƒ‰ํ•˜์—ฌ ๋น„์–ด์žˆ๋Š” ๊ณณ์„ ์ฐพ์•„ ์ด๋™ํ•œ๋‹ค.

๋ฒ”์œ„ ๋ฐ–์œผ๋กœ ์ด๋™ํ•  ๋•Œ๋Š” ์ด์–ด์ง„ ๊ณณ์„ ์ž˜ ์ƒ๊ฐํ•˜์—ฌ ์ด๋™ํ•œ๋‹ค.

 

 

 - my solution (Java)

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 _27211_ { // ๋„๋„› ํ–‰์„ฑ
	static int arr[][], result, n, m;
	static boolean visited[][];
	static int dx[]= {-1,1,0,0};
	static int dy[]= {0,0,-1,1};

	public static void main(String[] args) throws IOException {
		BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer(bf.readLine());

		n=Integer.parseInt(st.nextToken());
		m=Integer.parseInt(st.nextToken());

		arr=new int[n][m];
		visited=new boolean[n][m];
		result=0;

		for(int i=0; i<n; i++) {
			st=new StringTokenizer(bf.readLine());
			for(int j=0; j<m; j++) {
				arr[i][j]=Integer.parseInt(st.nextToken());
				if(arr[i][j]==1) visited[i][j]=true;
			}
		}
		for(int i=0; i<n; i++) {
			for(int j=0; j<m; j++) {
				if(!visited[i][j]) {
					visited[i][j]=true;
					result+=1;
					search(i,j);
				}
			}
		}
		System.out.println(result);
	}

	private static void search(int i, int j) {
		Queue<int[]> queue=new LinkedList<>();
		queue.add(new int[] {i,j});

		while(!queue.isEmpty()) {
			int temp[]=queue.poll();
			for(int k=0; k<4; k++) {
				int x=temp[0]+dx[k];
				int y=temp[1]+dy[k];
				if(x==-1) x= n-1;
				if(y==-1) y= m-1;
				if(x==n) x=0;
				if(y==m) y=0;
				if(x>=0 && x<n && y>=0 && y<m && !visited[x][y]) {
					visited[x][y]=true;
					queue.add(new int[] {x,y});
				}
			}
		}
	}
}

 

Main

-  n, m ์ž…๋ ฅ

- arr : ๋„๋„› ์ •๋ณด

- visited : ๋ฐฉ๋ฌธ ์—ฌ๋ถ€

- result: ํƒํ—˜ํ•  ์ˆ˜ ์žˆ๋Š” ๊ตฌ์—ญ์˜ ๊ฐœ์ˆ˜

- ๋„๋„› ํ–‰์„ฑ ์ •๋ณด๋ฅผ ์ž…๋ ฅ๋ฐ›์€ ํ›„ ์ˆฒ์œผ๋กœ ๋ง‰ํ˜€ ์žˆ๋Š” ๊ณณ์ด๋ผ๋ฉด ๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋ฅผ true๋กœ ์ €์žฅ

- ์ „์ฒด ๋„๋„› ํ–‰์„ฑ์„ ํƒํ—˜ํ•˜๋ฉฐ ์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๊ณณ์ด๋ผ๋ฉด ํƒํ—˜์„ ์‹œ์ž‘

 

Search

- queue๊ฐ€ ๋นŒ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๋ฉด์„œ ๊ฐ’์„ ํ•˜๋‚˜ ๋ฝ‘์•„ ์ƒํ•˜์ขŒ์šฐ ํƒ์ƒ‰

- ์ƒํ•˜์ขŒ์šฐ๋ฅผ ํƒ์ƒ‰ํ•˜๋ฉฐ ๋ฒ”์œ„ ๋ฐ–์ด๋ฉด ๋„๋„› ํ–‰์„ฑ์ด ์ด์–ด์ ธ ์žˆ์œผ๋ฏ€๋กœ ์ขŒํ‘œ๋ฅผ ์ˆ˜์ •ํ•˜์—ฌ ๋ฐฉ๋ฌธ ํ‘œ์‹œ ๋ฐ queue์— ์ถ”๊ฐ€

 


์ƒ๊ฐ๐Ÿค”