-
백준(BOJ) 9944번 NxM 보드 완주하기알고리즘 풀이/백준(Boj) 2019. 10. 13. 18:14
문제 : https://www.acmicpc.net/problem/9944
9944번: NxM 보드 완주하기
문제 N×M 보드 위에서 할 수 있는 게임이 있다. 보드는 크기가 1×1인 정사각형 칸으로 나누어져 있다. 보드의 각 칸은 빈 칸 또는 장애물이다. 장애물은 아래 그림에선 어두운 사각형으로 표시되어져 있다. 게임을 시작하려면 보드의 빈 칸 위에 공을 하나 놓아야 한다. 아래 그림에서 공은 회색 점으로 표시되어져 있다. 게임은 단계로 이루어져 있고, 각 단계는 아래와 같이 구성되어져 있다. 위, 아래, 오른쪽, 왼쪽 중 방향 하나를 고른 다음, 그 방향으로
www.acmicpc.net
풀이 :
완전 탐색을 이용하여 각 공이 될수 있는 지점마다 재귀호출을 통해 구하자. 선택된 각 지점에서는 상하좌우
방향으로 쭉 가면서 '.' 인 지점을 모두 방문하여야 종료하게 된다.
코드 ( C++ )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; const int dy[4] = { 1,-1,0,0 }; const int dx[4] = { 0,0,1,-1 }; string board[31]; int n, m; int visited[31][31]; bool check(int y, int x) { if (y >= 0 && y < n && x >= 0 && x < m) return true; return false; } int solve(int y, int x, int num) { if (num == 0) { return 0; } int ret = -1; for (int i = 0; i < 4; ++i) { int ny = y + dy[i]; int nx = x + dx[i]; while (check(ny,nx) && !visited[ny][nx] && board[ny][nx] == '.') { num--; visited[ny][nx] = true; ny += dy[i]; nx += dx[i]; } ny -= dy[i]; nx -= dx[i]; if (ny != y || nx != x) { int cand = solve(ny,nx,num); if (cand != -1) { if (ret == -1 || ret > cand+1) { ret = cand+1; } } } //돌려놓기 while (ny != y || nx != x) { visited[ny][nx] = false; num++; ny -= dy[i]; nx -= dx[i]; } } return ret; } int main() { int cnt = 1; while (cin >> n >> m) { int num = 0; for (int i = 0; i < n; ++i) { cin >> board[i]; for (int j = 0; j < m; ++j) { if (board[i][j] == '.') num++; } } int ret = -1; for(int i=0; i<n; ++i) for (int j = 0; j < m; ++j) { if (board[i][j] == '.') { visited[i][j] = 1; int cand = solve(i, j, num-1); if (cand != -1) { if (ret == -1 || ret > cand) { ret = cand; } } visited[i][j] = 0; } } cout << "Case " << cnt << ": " << ret << "\n"; cnt++; } return 0; } '알고리즘 풀이 > 백준(Boj)' 카테고리의 다른 글
백준(BOJ) 2422번 한윤정이 이탈리아에 가서 아이스크림을 사먹는데 (31) 2019.10.18 백준(BOJ) 4연산 (31) 2019.10.16 백준(BOJ) 12996번 Acka (31) 2019.10.13 백준(BOJ) 15562 톱니바퀴(2) (31) 2019.10.10 백준(BOJ) 2234번 성곽 (0) 2019.10.05