Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

백트래킹] 알파벳 - 백준 1987번 #86

Merged
merged 3 commits into from
Nov 11, 2020

Conversation

Kwakcena
Copy link
Owner

@Kwakcena Kwakcena commented Nov 11, 2020

알파벳

(0, 0) 에서 시작하여 상, 하, 좌, 우 방향으로 탐색하며 중복되지 않는 알파벳을 최대한으로 탐색하는 문제

나는 무엇을 할 수 있게 되었는가?

  • 이 문제처럼 문자열로 입력이 들어오는 경우 vector<string> str(개수) 를 통해 string 벡터를 선언하고 입력받을 수 있다.
vector<string> str(n);
for(int i=0; i<n; i++) {
  cin >> str[i];
}
  • 알파벳을 사용했는지 검사하는 check 배열의 경우 아스키 코드를 이용하면 배열의 사이즈를 0 ~ 25 까지로 조정할 수 있다.
vector<bool> check(26);
check[알파벳 - 'A'] = true;
// 'A'는 65이므로 대문자 알파벳 A ~ Z는 0부터 25가 된다.
  • 전역 변수를 쓰지 않고 재귀함수 내에서 사용되는 변수를 이용해 최장거리값을 돌려받을 수 있다.
int go(vector<string> &board, vector<bool> &check, int y, int x)
{
  int ans = 0;
  for (int i = 0; i < 4; i++)
  {
    int ny = y + dy[i];
    int nx = x + dx[i];

    if (0 <= ny && ny < board.size() && 0 <= nx && nx < board[0].size())
    {
      if (check[board[ny][nx] - 'A'] == false)
      {
        check[board[ny][nx] - 'A'] = true;
        int next = go(board, check, ny, nx);
        if(ans < next) {
          ans = next;
        }
        check[board[ny][nx] - 'A'] = false;
      }
    }
  }
  return ans + 1;
}

go 함수로 상하좌우에 더 이상 갈 곳이 없을 때 맨 마지막 재귀는 ans + 1값을 return 할 것이다.
ans는 0이었으므로, 1을 return 할 것이고, 맨 마지막 재귀를 호출했던 함수는 next에 1이 저장된다. 그때의 ans 는 0이었고, next값이 더 크므로 ans는 1이 된다.
재귀가 호출되어 돌아오는 값 만큼 증가하게 되고, 최초의 위치인 (0, 0)에 왔을 때는 최장거리값이 ans에 담겨있을 것이다.

- 재귀를 이용해서 방문했던 알파벳에 방문하지 않도록 한다.
- dfs를 이용하여 상하좌우의 알파벳을 탐색하였다.
- string, vector 라이브러리를 사용한다.
- 알파벳 사용 여부 체크는 알파벳 - 'A' 와 같이 할 수 있다.
시간초과가 나지만 python으로 풀었을 경우 코드를 작성해보았다
@Kwakcena Kwakcena merged commit d2635f9 into master Nov 11, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

전역변수를 쓰지 않고 dfs에서 값 돌려받기
1 participant