방향 배열

From_A_To_Z·2026년 1월 24일

알고리즘

목록 보기
2/10

  • 2차원 좌표 상에서 한 점을 기준으로 상하좌우 좌표를 구할 때 사용하는 배열
  • 방향 배열은 BFS, Flood Fill 등 다른 알고리즘에서 활용될 수 있음
  • 이미지 출처: 나노 바나나 프로 (Nano Banana Pro)

코드 예시 (Java)

import java.io.*; 
import java.util.*;//

public class Main {
	static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	static StringTokenizer st;
	
	//이차원 배열-> (0,0)~(3,3)의 좌표가 있을것이고,각각의 val는 밑에 적혀있음
	static int arr[][] = {
			{1,2,3,4},
			{5,6,7,8},
			{9,1,2,3},
			{4,5,6,7}
	};
	static int dy[] = {-1,1,0,0};
	static int dx[] = {0,0,-1,1};
	public static void main(String[] args) {
		int sty, stx;
		
		st = new StringTokenizer(br.readLine());
		sty = Integer.parseInt(st.nextToken());
		stx = Integer.parseInt(st.nextToken());

		//4방향(상하좌우)에 저장된 val출력하고 싶다
		for(int i=0; i<4; i++) {
			int ny = sty + dy[i];
			int nx = stx + dx[i];
			// || : 저중 하나만 걸려도 true
			if(ny<0 || ny>=4 || nx<0 || nx>=4)continue;
			System.out.println(arr[ny][nx]);
		}
	}
}
profile
What goes around comes around.

0개의 댓글