-
SWEA 1954. 달팽이 숫자PS 2023. 11. 18. 01:22
https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PobmqAPoDFAUq
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
문제 풀이
2차원 배열을 생성한 뒤 출력형식에 맞게 값을 갱신해주었다.
문제에선 우, 하, 좌, 상 순으로 방향을 바꿔가며 값을 갱신해주고 있는 것을 볼 수 있다.
격자탐색 문제처럼 dx, dy를 생성해주고 배열을 넘어가거나, 값이 갱신된 적이 있다면 방향을 갱신해주는 식으로 풀이하였다.
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Main { static int[] dx = {0, 1, 0, -1}; static int[] dy = {1, 0, -1, 0}; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int T = Integer.parseInt(br.readLine()); for(int test_case = 1; test_case <= T; test_case++){ sb.append("#").append(test_case).append("\n"); int N = Integer.parseInt(br.readLine()); int[][] answer = new int[N][N]; int x = 0; int y = 0; int d = 0; for(int i = 1; i <= N * N; i++){ answer[x][y] = i; int nx = x + dx[d]; int ny = y + dy[d]; if(nx < 0 || ny < 0 || nx >= N || ny >= N || answer[nx][ny] != 0){ d = (d+1) % 4; x += dx[d]; y += dy[d]; continue; } x = nx; y = ny; } for(int i = 0; i < N; i++){ for(int j = 0; j < N; j++){ sb.append(answer[i][j]).append(" "); } sb.append("\n"); } } System.out.println(sb); } }
'PS' 카테고리의 다른 글
프로그래머스 양과늑대 (0) 2024.09.30 SWEA 1767 프로세서 연결하기 (1) 2024.02.28 SWEA 1249. [S/W 문제해결 응용] 4일차 - 보급로 (0) 2023.11.18 SWEA 1206. [S/W 문제해결 기본] 1일차 - View (0) 2023.11.16 Java 1253 좋다 (0) 2023.09.11