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

Java 2차원 맵 탐색을 위한 BFS

계란💕 2022. 4. 28. 20:43
<hide/>
package first;

import java.security.KeyPair;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.lang.*;

public class TwoDimensionDFS {
	static int MAX_COUNT = 101;
	static int DIRECTION = 4;
	static int[][] DirMatrix = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
	
	static int ColumnCnt;
	static int RowCnt;
	static int cnt = 0;
	
	static int[][] Array = new int[MAX_COUNT][2];
	static int[][] AdjMatrix = new int[MAX_COUNT][MAX_COUNT];
	static int[][] VisitMatrix = new int[MAX_COUNT][MAX_COUNT];
	static Queue<Integer> queueRow = new LinkedList<>();
	static Queue<Integer> queueCol = new LinkedList<>();
	
	
	public static void main(String[] args) {
		
		Scanner scan = new Scanner(System.in);
		ColumnCnt = scan.nextInt();
		RowCnt = scan.nextInt();
			
		for(int i = 1; i <= RowCnt; ++i ) {
			for(int j = 1; j <= ColumnCnt; ++j) {
				if(0 == VisitMatrix[i][j] &&  1 == AdjMatrix[i][j]) {
					++cnt;
					BFSmethod(i, j);
				}
			}
		}
		System.out.println(cnt);
	}

	public static void BFSmethod(int _StartRow, int _StartCol) {
	
		VisitMatrix[_StartRow][_StartCol] = 1;
		queueRow.add(_StartRow);
		queueCol.add(_StartCol);
						
		System.out.printf("start: (%d, %d)\n" , _StartRow, _StartCol);
		
		while(false == queueRow.isEmpty() ) {
		
			int CurrRow =  queueRow.poll();
			int CurrCol = queueCol.poll(); 
			
			
			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( 0 == AdjMatrix[nextRow][nextCol] &&
					1 <= nextRow && nextRow <= RowCnt &&
					1 <= nextCol && nextCol <= ColumnCnt){	
				
					VisitMatrix[nextRow][nextCol] = 1;
					queueRow.add(nextRow);
					queueCol.add(nextCol);
					System.out.printf("(%d, %d -> (%d, %d))\n" , _StartRow, _StartCol, nextRow, nextCol);
				}
			}
		}
	}
}