본문 바로가기

개발/알고리즘

백준 1987 알파벳 C++

문제

www.acmicpc.net/problem/1987

 

1987번: 알파벳

세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다. 말은 상하좌우로 인접한 네 칸 중의 한 칸으

www.acmicpc.net

코드

#include <bits/stdc++.h>

using namespace std;

int r, c, answer = 1, arr[21][21], alphabet[26], dy[] = { -1, 0, 1, 0 }, dx[] = { 0, 1, 0, -1 };
char ch;

void input()
{
	cin >> r >> c;
	for (int i = 0; i < r; i++)
	{
		for (int j = 0; j < c; j++)
		{
			cin >> ch;
			arr[i][j] = ch - 'A';
		}
	}
}

int go(int y, int x, int num)
{
	for (int i = 0; i < 4; i++)
	{
		int ny = dy[i] + y;
		int nx = dx[i] + x;
		if (ny >= r || ny < 0 || nx >= c || nx < 0 || alphabet[arr[ny][nx]])
			continue;

		alphabet[arr[ny][nx]] = 1;
		answer = max(answer, go(ny ,nx, num+1));
		alphabet[arr[ny][nx]] = 0;
	}

	return num;
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	input();

	alphabet[arr[0][0]] = 1;
	go(0, 0, 1);
	cout << answer << '\n';
	return 0;
}

'개발 > 알고리즘' 카테고리의 다른 글

프로그래머스 실패율 javaScript  (0) 2021.05.07
백준 1094 막대기 C++  (0) 2021.05.05
백준 17298 오큰수 C++ (Stack)  (0) 2021.05.03
백준 17070 파이프옮기기1 C++  (0) 2021.04.18
백준 1647 도시 분할 계획 C++  (0) 2021.04.17