작성일 :

문제 링크

8712번 - Wężyk

설명

1부터 n²까지의 수를 n행 n열에 채우되, 홀수 번째 행은 왼쪽에서 오른쪽으로, 짝수 번째 행은 오른쪽에서 왼쪽으로 출력하는 문제입니다.


접근법

각 행이 담당하는 구간은 연속된 n개의 수입니다. 홀수 행이면 시작값부터 증가시키며 출력하고, 짝수 행이면 끝값부터 감소시키며 출력하면 됩니다.



Code

C#

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
using System;
using System.Text;

class Program {
  static void Main() {
    var n = int.Parse(Console.ReadLine()!);
    var sb = new StringBuilder();

    for (var row = 0; row < n; row++) {
      var start = row * n + 1;
      var end = start + n - 1;

      for (var col = 0; col < n; col++) {
        if (col > 0)
          sb.Append(' ');

        if (row % 2 == 0)
          sb.Append(start + col);
        else
          sb.Append(end - col);
      }
      sb.Append('\n');
    }

    Console.Write(sb);
  }
}

C++

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
#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n; cin >> n;

  for (int row = 0; row < n; row++) {
    int start = row * n + 1;
    int end = start + n - 1;

    for (int col = 0; col < n; col++) {
      if (col)
        cout << ' ';

      if (row % 2 == 0)
        cout << start + col;
      else
        cout << end - col;
    }
    cout << "\n";
  }

  return 0;
}

Tags: 8712, BOJ, C#, C++, 구현, 백준, 알고리즘, 출력

Categories: ,