백준 1987번 알파벳 C++ DFS

빵어 ㅣ 2024. 10. 30. 17:02

#include <iostream>
using namespace std;

int r, c;
char arr[21][21]{};
int maxResult = 1;
bool visited[26]{};

const int dy[4]{ 1,-1,0,0 };
const int dx[4]{ 0,0,-1, 1 };

void DFS(int y, int x, int curResult)
{
	for (int i = 0; i < 4; ++i) {
		int ny = dy[i] + y;
		int nx = dx[i] + x;

		if (ny < 0 || nx < 0 || ny >= r || nx >= c)
			continue;

		int curAlpha = arr[ny][nx] - 'A';

		if (visited[curAlpha]) {
			maxResult = max(curResult, maxResult);
			continue;
		}

		visited[curAlpha] = true;
		DFS(ny, nx, curResult + 1);
		visited[curAlpha] = false;
	}
}

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

	cin >> r >> c;
	for (int i = 0; i < r; ++i) 
		for (int j = 0; j < c; ++j) 
			cin >> arr[i][j];

	visited[arr[0][0] - 'A'] = true;

	DFS(0, 0, 1);

	cout << maxResult;

	return 0;
}

 

 

반례 1 1 A

maxResult 초기화를 1로 하고 시작해야한다.

 

'알고리즘 공부' 카테고리의 다른 글

백준 1904번 01타일 C++  (0) 2024.10.31
백준 9251번 LCS C++  (0) 2024.10.31
백준 2110번 공유기 설치 C++  (0) 2024.10.29
백준 1753번 최단경로 C++  (0) 2024.10.24
백준 14052번 연구소 C++  (0) 2024.10.17