https://swexpertacademy.com/main/main.do?
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
DFS를 이용해서 풀었다.
기초중에 기초인데, DFS 사용을 어려워해서 걱정이다.
import java.util.Scanner;
public class P1954 {
static int n;
static int[][] a;
static int[] dx={-1,0,1,0}, dy={0,1,0,-1};
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int t=1; t<=T; t++) {
n = sc.nextInt();
a = new int[n][n];
System.out.println("#"+t);
solution(1, 0, 0, 0);
}
}
public static void solution(int start,int x, int y, int dir){
if(start==n*n){
a[x][y] = start;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
} else {
a[x][y] = start;
int nx = x + dx[dir];
int ny = y + dy[dir];
if(nx<0 || nx>=n || ny<0 || ny>=n || a[nx][ny]!=0){
dir = (dir+1)%4;
}
x = x + dx[dir];
y = y + dy[dir];
solution(start+1, x, y, dir);
}
}
}
'알고리즘 > SWEA' 카테고리의 다른 글
[SWEA] 1244. [S/W 문제해결 응용] 2일차 - 최대 상금 (0) | 2022.11.09 |
---|---|
[SWEA] 1974. 스도쿠 검증 (0) | 2022.11.08 |
[SWEA] 1961. 숫자 배열 회전 (0) | 2022.11.08 |
[SWEA] 1928. Base64 Decoder (0) | 2022.11.07 |
[SWEA] 1204. [S/W 문제해결 기본] 1일차 - 최빈수 구하기 (0) | 2022.11.07 |