-
[C++] ์ผ์ฑ 2105. [๋ชจ์ SW ์ญ๋ํ ์คํธ] ๋์ ํธ ์นดํ์ฝ๋ฉํ ์คํธ/์ฝ๋ฉํ ์คํธ ์ฐ์ต 2020. 10. 27. 18:22728x90
(2์๊ฐ) ์๋ ์ ํ์ด์ ๋นจ๋ฆฌ ํ์๋๋ฐ ์ฝ๋๊ฐ ๋๋ฌด ์์ด๋ป์ ๋ค๋ฅธ ๋ฐฉํฅ์ผ๋ก ํ์ด๋ณผ๋ ค๊ณ ๊ณ์ ๋ถ์ก์์.
4๋ฐฉํฅ ๋ชจ๋ ํ์ธํ ํ์์์ด ์์ ๋๋ฐฉํฅ์ด ์ด๋ํ๋งํผ ๋ฐ๋๋ก backtracking ํด์ฃผ์๋ ์๊ฐ์ผ๋ก ์ ๊ทผ
#include<iostream> #include<vector> using namespace std; int N; int dessert[20][20]; int dir[4][2] = { {-1, 1}, {1, 1}, {1, -1}, {-1, -1} }; int dessertNum; bool outRangeCheck(int x, int y) { if (x < 0 || y < 0 || x >= N || y >= N) return true; return false; } void dessertTour(int x, int y, vector<int> include, vector<int> path) { int direction = path.back(); if (direction == 2) { // ๋ ๋ฐฉํฅ์ ์ด๋ํ์ผ๋ฉด ๋ ๋ฐฉํฅ์ด ์ด๋ํ ๋งํผ ๋ฐ๋ํธ์ผ๋ก backtracking path.pop_back(); for (int i = 0; i < path.size(); i++) { x = x + dir[path[i] + 2][0]; y = y + dir[path[i] + 2][1]; int value = dessert[x][y]; if (outRangeCheck(x, y)) return; for (int i = 0; i < include.size(); i++) { if (include[i] == value) return; } include.push_back(value); } int includeCount = include.size(); if (dessertNum < includeCount) dessertNum = includeCount; return; } int new_x = x + dir[direction][0]; int new_y = y + dir[direction][1]; int value = dessert[new_x][new_y]; if (outRangeCheck(new_x, new_y)) return; for (int i = 0; i < include.size(); i++) { if (include[i] == value) return; } include.push_back(value); path.push_back(direction); dessertTour(new_x, new_y, include, path); path.pop_back(); path.push_back(direction + 1); dessertTour(new_x, new_y, include, path); path.pop_back(); } int main() { int T; cin >> T; for (int t = 1; t <= T; t++) { cin >> N; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cin >> dessert[i][j]; } } dessertNum = -1; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { vector<int> include; vector<int> path; path.push_back(0); dessertTour(i, j, include, path); } } cout << "#" << t << " " << dessertNum << endl; } return 0; }
728x90'์ฝ๋ฉํ ์คํธ > ์ฝ๋ฉํ ์คํธ ์ฐ์ต' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ