자료구조와 알고리듬 With Java/[Study] BAEKJOON 프로그래머스 CodeUp LeetCode

Code up 그림 개수 세기

계란💕 2022. 4. 20. 00:59

  Ex) 2차원 배열 

<hide/>
import java.util.*;
public class DfsCountPicture {
	static int DIRECTION = 4;
	static int MAX_COUNT = 101;
	static int [][] g_nAdjMatrix = new int[MAX_COUNT][MAX_COUNT];
	static int [][] g_nVisitMatrix = new int[MAX_COUNT][MAX_COUNT];
	static int g_uVCount = 10, g_uECount;
	static int [][]g_nDirMatrix = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
		
	public static void main(String[] args) {

			int  uPictureCount = 0;
			Scanner scan = new Scanner(System.in);
			for(int i = 1; i <= g_uVCount;++i) {		// 행렬 입력
				for(int j = 1; j <= g_uVCount; ++j) {
					g_nAdjMatrix[i][j] = scan.nextInt();
				}
			}
			for(int i = 1; i <= g_uVCount;++i) {
				for(int j = 1; j <= g_uVCount; ++j) {
					if(0 == g_nVisitMatrix[i][j]  &&  1 == g_nAdjMatrix[i][j]) {// 아직 미방문 & 이어져있으면
						++uPictureCount;
						DFSmethod(i, j);
					}
				}	
			}
			System.out.println(uPictureCount);
	}	
		
	public static void DFSmethod(int _uCurrCRow, int _uCurrVCol) {
		
		int uPictureCount = 0;
		g_nVisitMatrix[_uCurrCRow][_uCurrVCol] = 1;		// 방문 등록
		for(int i = 0; i < DIRECTION; ++i) {
			
			int uNextVRow = _uCurrCRow + g_nDirMatrix[i][0];	
            // 현재 행 + [1,-1, 0, 0]
			int uNextVCol = _uCurrVCol + g_nDirMatrix[i][1];		
            // 현재 열 + [0, 0, -1, 1]
			if(1 == g_nVisitMatrix[uNextVRow][uNextVCol]) continue;
			if(1 == g_nAdjMatrix[uNextVRow][uNextVCol]
				&& 1 <= uNextVRow && uNextVRow <= g_uVCount
				&& 1 <= uNextVCol && uNextVCol <= g_uVCount){
					DFSmethod(uNextVRow, uNextVCol);
			}
		}
	}	
}

 

  - 입력 코드 1

<hide/>
입력
0 0 0 1 1 1 1 0 0 0
0 0 0 1 1 1 1 0 0 0
1 1 1 0 0 0 0 1 1 1
1 0 1 0 0 0 0 1 0 1
1 1 1 0 1 1 0 1 1 1
0 0 0 0 1 1 0 0 0 0
1 1 1 1 0 0 1 1 1 1
1 0 0 1 0 0 1 0 0 1
1 0 0 1 0 0 1 0 0 1
1 1 1 1 0 0 1 1 1 1

출력
6

 

  - 입력 코드 2

<hide/>
입력
1 1 0 1 1 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
1 0 1 1 1 0 0 0 0 0
0 0 1 1 1 0 0 0 0 0
0 0 1 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

출력 
4