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

Code up 2605 캔디팡

계란💕 2022. 4. 22. 16:43

  Ex)

<hide/>
import java.util.Arrays;
import java.util.Scanner;
public class CandyPang {
/*

7
2 1 5 1 1 3 4
2 1 5 1 3 5 3
2 3 4 5 2 2 4
4 4 3 2 3 1 3 
4 3 5 3 1 4 3
5 4 4 3 3 5 5 
2 1 3 5 1 1 2

 */
	static int uCnt = 0;
	static int Size = 7;
	static int[][] VisitMatrix = new int[ 200][200];
	static int[][]AdjMatrix = new int[200][200];
	static int DIRECTION = 4;
	static int[][] DirMatrix = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
	static int CandyCount = 0;
	
	public static void main(String[] args) {
		
		Scanner scan = new Scanner(System.in);
	//	Size = scan.nextInt();
		for(int i = 1; i <= Size; ++i){
			for(int j = 1; j <= Size; ++j  ) {
				AdjMatrix[i][j] = scan.nextInt();
			}
		}
		/*
	 	인접행렬 출력 확인
		for(int i= 1; i <= Size; ++i){
			for(int j = 1; j <= Size; ++j  ) {
				System.out.print( AdjMatrix[i][j] + " ");
			}
			System.out.println();
		}
		*/
		for(int i = 1; i <= Size; ++i) {
			for(int j = 1; j <= Size; ++j) {
				DFSmethod(i, j);
				if(2 <= uCnt) {
					++CandyCount;
	//				System.out.printf("CandyCount: %d\n", CandyCount);
				}
				uCnt = 0;	// 초기화시킨다.
			}
		}
		System.out.println(CandyCount);
	}
	
	public static void DFSmethod(int _CurrRow, int _CurrCol) {
		VisitMatrix[_CurrRow][_CurrCol] = 1;
		for(int i = 0; i < DIRECTION; ++i) {
			int nextRow = _CurrRow + DirMatrix[i][0];
			int nextCol = _CurrCol + DirMatrix[i][1];
			if(1 == VisitMatrix[nextRow][nextCol] ) continue;
			if(	AdjMatrix[_CurrRow][_CurrCol] == AdjMatrix[nextRow][nextCol] &&
					1 <= nextRow &&  nextRow <= Size && 
					1 <= nextCol &&  nextCol <= Size 	) {
							 ++uCnt;
					//		System.out.printf("(%d , %d) => (%d , %d)\n",_CurrRow, _CurrCol, nextRow, nextCol  ); 
							DFSmethod(nextRow, nextCol);	
			}	
		}
	} 
}

 

  Note)

입력

2 1 5 1 1 3 4
2 1 5 1 3 5 3
2 3 4 5 2 2 4
4 4 3 2 3 1 3 
4 3 5 3 1 4 3
5 4 4 3 3 5 5 
2 1 3 5 1 1 2

출력

4

  - 방향 매트릭스가 필요하다.

  - main함수에서 DFSmethod를 실행할 때마다 (uCnt가 2보다 클 때만) CandyCount를 추가한다.

  - 2보다 작은 경우에는  꼭 uCnt를 0으로 꼭 초기화해준다.