[C++] 백준 24725 엠비티아이

2022. 4. 24. 14:33알고리즘

이 문제는 어렸을 때 많이 해봤던 단어 퍼즐 문제다. 처음에 dfs로 풀어야겠다 생각하고 막상 도전했는데 한 방향 찾기가 익숙치 않아 푸는 데 많은 도움을 받은 문제다. 결국 노가다로 풀었다. 

#include <bits/stdc++.h>
#define MAX 201
using namespace std;

int n, m;
string Map[MAX];
int dx[8] = { 0, 0, 1, -1, 1, -1, 1, -1 };
int dy[8] = { 1, -1, 0, 0, 1, 1, -1, -1 };

bool Check(int y, int x) {
	return y < 0 || x < 0 || y > n || x > m;
}

int dfs(int y, int x) { //그냥 노가다
	int ret = 0;
	for (int i = 0; i < 8; i++) {
		int nx = x + dx[i], ny = y + dy[i];
		if (Check(ny, nx)) continue;
		if (Map[ny][nx] == 'N' || Map[ny][nx] == 'S') {
			nx += dx[i]; ny += dy[i];
			if (Check(ny, nx)) continue;
			if (Map[ny][nx] == 'F' || Map[ny][nx] == 'T') {
				nx += dx[i]; ny += dy[i];
				if (Check(ny, nx)) continue;
				if (Map[ny][nx] == 'P' || Map[ny][nx] == 'J') ret++;
			}
		}
	}
	return ret;
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr); cout.tie(nullptr);
	cin >> n >> m;
	for (int i = 0; i < n; i++) 
		cin >> Map[i];

	int res = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (Map[i][j] == 'E' || Map[i][j] == 'I') //첫 글자가 E나 I일 때만 탐색
				res += dfs(i, j);
		}
 	}
	cout << res;
}