알고리즘
백준 1189번 컴백홈 C++
영춘권의달인
2022. 5. 28. 14:15
백트래킹을 이용하였다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using ll = long long;
int r, c, k;
int ans = 0;
pair<int, int> start, target;
int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };
vector<vector<char>> board(5, vector<char>(5));
vector<vector<bool>> visited(5, vector<bool>(5, false));
void BT(int dist, pair<int, int> curr) {
if (dist >= k) {
if (curr == target) ans++;
return;
}
if (visited[target.first][target.second]) return;
for (int i = 0; i < 4; i++) {
int nextRow = curr.first + dRow[i];
int nextCol = curr.second + dCol[i];
if (nextRow < 0 || nextRow >= r) continue;
if (nextCol < 0 || nextCol >= c) continue;
if (board[nextRow][nextCol] == 'T') continue;
if (visited[nextRow][nextCol]) continue;
visited[nextRow][nextCol] = true;
BT(dist + 1, { nextRow,nextCol });
visited[nextRow][nextCol] = false;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> r >> c >> k;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cin >> board[i][j];
}
}
start = { r - 1,0 };
target = { 0,c - 1 };
visited[start.first][start.second] = true;
BT(1, start);
cout << ans;
};