🙇‍♀️미로 탐색(DFS)

7*7 격자판 미로를 탈출하는 경로의 가지수를 출력하는 프로그램을 작성하세요.
출발점은 격자의 (1, 1) 좌표이고, 탈출 도착점은 (7, 7)좌표이다.
격자판의 1은 벽이고, 0은 통로이다. 격자판의 움직임은 상하좌우로만 움직인다.
미로가 다음과 같다면

maze

위의 지도에서 출발점에서 도착점까지 갈 수 있는 방법의 수는 8가지이다.

▣ 입력설명
첫 번째 줄부터 7*7 격자의 정보가 주어집니다.

▣ 출력설명
첫 번째 줄에 경로의 가지수를 출력한다.

▣ 입력예제 1 
0 0 0 0 0 0 0
0 1 1 1 1 1 0
0 0 0 1 0 0 0
1 1 0 1 0 1 1
1 1 0 0 0 0 1
1 1 0 1 1 0 0
1 0 0 0 0 0 0

▣ 출력예제 1
8

🚀풀이

이전의 경로 탐색 문제와 비슷하여 금방 풀었다.

이것도 모든 경로를 탐색해야하므로 방문하고 DFS돌리고 방문을 원복해야한다.

int dy[] = { -1, 0, 1, 0 };
int dx[] = { 0, 1, 0, -1 };
void DFS(pair<int, int> pos)
{
	if (pos.first == 7 && pos.second == 7)
		res++;
	for (int i = 0; i < 4; ++i)
	{
		int ny = pos.first + dy[i];
		int nx = pos.second + dx[i];

		if (ny < 1 || nx < 1 || ny > 7 || nx > 7) // 보드 범위 체크
			continue;
		if (board[ny][nx] == 1) // 연결 여부 체크
			continue;
		if (visited[ny][nx]) // 방문 여부 체크
			continue;

		visited[pos.first][pos.second] = true; // 방문 체크
		DFS({ ny, nx });
		visited[pos.first][pos.second] = false; // 방문 원복
	}
}

이전의 코드 경험이 좀 쌓인듯하여 좋았다.

🚀전체 코드

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include<iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

int board[8][8];
int visited[8][8];
pair<int, int> Gpos;
int res = 0;
void setting()
{
	for (int y = 1; y <= 7; ++y)
		for (int x = 1; x <= 7; ++x)
			cin >> board[y][x];

	Gpos = { 1, 1 };
}

int dy[] = { -1, 0, 1, 0 };
int dx[] = { 0, 1, 0, -1 };
void DFS(pair<int, int> pos)
{
	if (pos.first == 7 && pos.second == 7)
		res++;
	for (int i = 0; i < 4; ++i)
	{
		int ny = pos.first + dy[i];
		int nx = pos.second + dx[i];

		if (ny < 1 || nx < 1 || ny > 7 || nx > 7)
			continue;
		if (board[ny][nx] == 1)
			continue;
		if (visited[ny][nx])
			continue;

		visited[pos.first][pos.second] = true;
		DFS({ ny, nx });
		visited[pos.first][pos.second] = false;
	}
}

void solve()
{
	setting();

	DFS(Gpos);

	cout << res;
}

int main() 
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	//freopen("input.txt", "rt", stdin);

	solve();

	return 0;
}