문제 - 정수를 나선형으로 배치하기

풀이
class Solution {
public int[][] solution(int n) {
int[][] answer = new int[n][n];
int value = 1;
int row = 0;
int col = 0;
int direction = 0;
while (value <= n * n) {
answer[row][col] = value++;
if (direction == 0) {
if (col == n - 1 || answer[row][col + 1] != 0) {
direction = 1;
row++;
} else {
col++;
}
} else if (direction == 1) {
if (row == n - 1 || answer[row + 1][col] != 0) {
direction = 2;
col--;
} else {
row++;
}
} else if (direction == 2) {
if (col == 0 || answer[row][col - 1] != 0) {
direction = 3;
row--;
} else {
col--;
}
} else if (direction == 3) {
if (row == 0 || answer[row - 1][col] != 0) {
direction = 0;
col++;
} else {
row--;
}
}
}
return answer;
}
}
설명
문제 - 특별한 이차원 배열 2

풀이
class Solution {
public int solution(int[][] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] != arr[j][i]) {
return 0;
}
}
}
return 1;
}
}
설명
문제 - 정사각형으로 만들기

풀이
class Solution {
public int[][] solution(int[][] arr) {
int rows = arr.length;
int cols = arr[0].length;
if (rows > cols) {
int[][] answer = new int[rows][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
if (j < cols) {
answer[i][j] = arr[i][j];
} else {
answer[i][j] = 0;
}
}
}
return answer;
} else if (cols > rows) {
int[][] answer = new int[cols][cols];
for (int i = 0; i < cols; i++) {
for (int j = 0; j < cols; j++) {
if (i < rows) {
answer[i][j] = arr[i][j];
} else {
answer[i][j] = 0;
}
}
}
return answer;
} else {
return arr;
}
}
}
설명
문제 - 이차원 배열 대각선 순회하기

풀이
class Solution {
public int solution(int[][] board, int k) {
int answer = 0;
for(int i =0; i<board.length; i++){
for(int j=0; j<board[0].length; j++) {
if(i+j <= k) {
answer += board[i][j];
}
}
}
return answer;
}
}
설명