Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- lv0
- 스프링부트 도커
- 삼각형의 완성조건
- lv2
- 백준
- 프로그래머스 자바
- 프로그래머스 문자열 정렬
- 자바
- Stack
- 문자열
- 스프링부트 도커 배포
- java
- 스택
- 큐
- Queue
- StringTokenizer
- 오름차순 정렬
- COS Pro
- 백준 N과 M 자바
- 클라이언트
- Programmers
- 버퍼
- 스프링부트 도커로 배포
- 프로그래머스 풀이
- Lv1
- 이진수 변환
- 프로그래머스
- 알고리즘
- index of
- SWEA
Archives
- Today
- Total
mun dev
[SWEA] D2 1954 달팽이 숫자 자바(Java) 본문
문제 링크
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
풀이
DFS 알고리즘을 활용해서 풀었다. 범위가 넘어가거나 다음칸이 채워져있지 않는 경우 방향을 바꿔준다.
D2문제 이지만 어려웠던 문제였다.....
풀이 코드
import java.io.*;
import java.util.*;
public class Solution {
public static int n;
public static int arr[][];
public static boolean visited[][];
public static int dx[] = { 0, 1, 0, -1 };
public static int dy[] = { 1, 0, -1, 0 };
public static void main(String[] args) throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int test_case = 1; test_case <= T; test_case++) {
n = sc.nextInt();
arr = new int[n][n];
visited = new boolean[n][n];
for (int i = 0; i < n; i++) {
Arrays.fill(visited[i], false);
}
dfs(0, 0, 0);
System.out.println("#"+test_case);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
public static void dfs(int dir, int x, int y) {
for (int i = 1; i <= n * n; i++) {
arr[x][y] = i;
visited[x][y] = true;
int cx = x + dx[dir];
int cy = y + dy[dir];
// 범위 넘어가거나, 다음칸이 채워져 있는 경우
if (cx < 0 || cy < 0 || cx >= n || cy >= n || visited[cx][cy]) {
dir = (dir + 1) % 4; // 방향바꿈
}
// 다음칸 지정
x = x + dx[dir];
y = y + dy[dir];
}
}
}
'알고리즘 > SWEA' 카테고리의 다른 글
[SWEA] D2 스도쿠 검증 자바(Java) (0) | 2023.11.19 |
---|---|
[SWEA] D3 2805 농작물 수확하기 자바(Java) (0) | 2023.11.19 |
[SWEA] D2 2001 파리퇴치 자바(Java) (0) | 2023.11.16 |
[SWEA] D3 5215 햄버거 다이어트 자바(Java) (0) | 2023.11.15 |
[SWEA] D2 1204 최빈수 구하기 자바(Java) (0) | 2023.11.15 |