우대각으로 테이블에 접근하자.
위의 그림처럼 우대각 순서대로 테이블에 접근하는 방법을 생각해보자.
필요한 규칙을 찾아보자.
모든 대각은 j==0인 칸에서 시작되며, j==6인 칸에서 끝난다.
j가 6에 도달했을 때 다음 대각의 첫 칸으로 옮긴 뒤,
테이블을 벗어난 대각을 만나면 순회를 종료한다.
코드로 직접 구현해보자.
while
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#define SIZE 6 | |
int main() | |
{ | |
int table[SIZE][SIZE]; | |
int i, j, v; | |
i = j = v = 0; | |
//! table[SIZE][0]에 도달했다면, | |
//! 모든 동작이 완료된 것 이다. | |
while (i != 0 || j != SIZE) | |
{ | |
//! 값을 대입함. | |
printf("table[%d][%d] == %d \n", i, j, v); | |
table[i][j] = v; | |
//! 다음에 접근할 점의 좌표를 구한다. | |
//! 한 대각선의 차례가 끝났다면 | |
//! 다음 대각선의 첫 좌표로 이동한다. | |
i++, j++, v++; | |
if (j == SIZE) | |
{ | |
j = SIZE - i + 1; | |
i = 0; | |
} | |
} | |
} |
for
조금만 더 생각해보면 (i, j)표현은 (대각번호, 요소번호) 표현으로 상호변환될 수 있다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int main() | |
{ | |
int table[SIZE][SIZE]; | |
int v = 0; | |
//! line : 현재 대각의 인덱스. | |
//! idx : 현대 대각의 idx번째 요소. | |
for (int line = 0; line < SIZE; line++) | |
{ | |
for (int idx = 0; line + idx < SIZE; idx++) | |
{ | |
int i = idx; | |
int j = line + idx; | |
printf("table[%d][%d] == %d \n", i, j, v); | |
table[i][j] = v++; | |
} | |
} | |
} |
좌대각으로 테이블에 접근하자.
우대각으로 접근하는 for문 코드에서 i와 j를 바꾸면 된다.
'# 미사용' 카테고리의 다른 글
안드로이드, 비트 계산기 (0) | 2018.09.26 |
---|---|
[백준 11066] 파일 합치기 (0) | 2018.09.16 |
[백준 1520] 내리막길 문제풀이 (0) | 2018.08.16 |
[백준 2156] 포도주 시식 문제풀이 (0) | 2018.08.15 |
[백준 2293] 동전 1 풀이노트 (0) | 2018.08.09 |