작성일 :

문제 링크

5367번 - Target Practice

설명

크기가 주어졌을 때, 바깥은 사각형이고 안쪽에는 X 모양이 있는 표적을 출력하는 문제입니다.


접근법

첫 줄과 마지막 줄은 양 끝이 |이고 가운데가 -로 채워진 형태입니다.

가운데 줄들은 양 끝을 |로 두고, 내부에서 두 대각선 위치에만 *를 놓으면 됩니다. 즉 i번째 줄에서는 왼쪽에서 i번째와 오른쪽에서 i번째 위치에 *를 찍고, 나머지는 공백으로 채웁니다.

이 규칙대로 위에서부터 아래까지 한 줄씩 출력하면 원하는 모양이 만들어집니다.



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

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

    sb.Append('|').Append(new string('-', n - 2)).AppendLine("|");

    for (int i = 1; i <= n - 2; i++) {
      char[] line = new string(' ', n).ToCharArray();
      line[0] = '|';
      line[n - 1] = '|';
      line[i] = '*';
      line[n - 1 - i] = '*';
      sb.AppendLine(new string(line));
    }

    sb.Append('|').Append(new string('-', n - 2)).AppendLine("|");

    Console.Write(sb.ToString());
  }
}

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

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

  int n;
  cin >> n;

  cout << "|" << string(n - 2, '-') << "|\n";

  for (int i = 1; i <= n - 2; i++) {
    string line(n, ' ');
    line[0] = '|';
    line[n - 1] = '|';
    line[i] = '*';
    line[n - 1 - i] = '*';
    cout << line << "\n";
  }

  cout << "|" << string(n - 2, '-') << "|\n";

  return 0;
}

Tags: 5367, BOJ, C#, C++, 구현, 문자열, 백준, 알고리즘

Categories: ,