백준 알고리즘(C++)

백준 15684번 사다리 조작 ( C++ )

coding232624 2024. 8. 21. 18:50

문제

https://www.acmicpc.net/problem/15684

 

해설

반복문을 돌며 사다리타기를 하는 방법을 구상해야함

2차원 배열을 통해 가로선의 위치를 기록하는 방식

 

코드

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <bits/stdc++.h>
using namespace std;
 
int n, m, h, ret = 7, a, b;
int visited[34][14];
 
bool check()
{
  for (int i = 1; i <= n; i++)
  {
    int start = i;
    for (int j = 1; j <= h; j++)
    {
      if (visited[j][start])
      {
        start++;
      }
      else if (visited[j][start - 1])
        start--;
    }
    if (start != i)
      return false;
  }
  return true;
}
 
void go(int start, int cnt)
{
  if (cnt > 3 || cnt >= ret)
    return;
  if (check())
  {
    ret = cnt;
    return;
  }
 
  for (int i = start; i <= h; i++)
  {
    for (int j = 1; j < n; j++)
    {
      if (visited[i][j] || visited[i][j - 1|| visited[i][j + 1])
        continue;
      visited[i][j] = 1;
      go(i, cnt + 1);
      visited[i][j] = 0;
    }
  }
}
 
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> n >> m >> h;
  for (int i = 0; i < m; i++)
  {
    cin >> a >> b;
    visited[a][b] = 1;
  }
 
  go(10);
  if (ret == 7)
  {
    cout << -1;
    return 0;
  }
  cout << ret;
}
cs