본문 바로가기
이론/코딩테스트

[백준] 1987번 알파벳 (DFS)

by 퇴근후개발 2022. 8. 8.
반응형

-문제

 

-코드

#include<iostream>
using namespace std;

int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };
int ch[26], r, c, res=0;
char map[20][20];

void DFS(int x, int y, int cnt)
{
	for (int i = 0; i < 4; i++)
	{
		int xx = x + dx[i];
		int yy = y + dy[i];
		if (xx < 0 || yy < 0 || xx >= r || yy >= c) continue;
		if (ch[map[xx][yy] - 'A'] == 0)
		{
			ch[map[xx][yy] - 'A'] = 1;
			DFS(xx, yy, cnt+1);
			ch[map[xx][yy] - 'A'] = 0;
		}
	}

	if (res < cnt) res = cnt;
}

int main()
{
	cin >> r >> c;
	for (int i = 0; i < r; i++)
	{
		for (int j = 0; j < c; j++)
		{
			cin >> map[i][j];
		}
	}
	ch[map[0][0] - 'A'] = 1;
	DFS(0,0,1);
	printf("%d", res);

	return 0;
}
반응형