#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <memory.h>
#include <climits>
using namespace std;
int N = 0, maxCore = 0, minWire = 0;
int dx[4] = { -1, 1, 0, 0 };
int dy[4] = { 0, 0, -1, 1 };
int board[100][100] = { 0, };
vector<pair<int, int>> coreList;
void connectCoreToPower(int v, int coreCount, int wireLen) {
if (v == coreList.size()) {
if (coreCount > maxCore) {
maxCore = coreCount;
minWire = wireLen;
}
else if (coreCount == maxCore) {
minWire = min(minWire, wireLen);
}
return;
}
for (int dir = 0; dir < 4; dir++) {
int nx = coreList[v].first;
int ny = coreList[v].second;
int count = 0;
while (true) {
nx += dx[dir];
ny += dy[dir];
if (nx < 0 || nx >= N || ny < 0 || ny >= N) break;
if (board[nx][ny] == 1) {
count = 0;
break;
}
count++;
}
// update board
int xpos = coreList[v].first;
int ypos = coreList[v].second;
for (int i = 0; i < count; i++) {
xpos += dx[dir];
ypos += dy[dir];
board[xpos][ypos] = 1;
}
if (count > 0) {
connectCoreToPower(v + 1, coreCount + 1, wireLen + count);
// reset board
xpos = coreList[v].first;
ypos = coreList[v].second;
for (int i = 0; i < count; i++) {
xpos += dx[dir];
ypos += dy[dir];
board[xpos][ypos] = 0;
}
}
else if (count==0) {
connectCoreToPower(v + 1, coreCount, wireLen);
}
}
}
int main(int argc, char** argv)
{
cin.tie(NULL);
ios_base::sync_with_stdio(false);
int test_case;
int T;
// freopen("input.txt", "r", stdin);
cin >> T;
for (test_case = 1; test_case <= T; ++test_case)
{
maxCore = INT_MIN;
minWire = INT_MAX;
coreList.clear();
int val = 0;
cin >> N;
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
cin >> val;
board[r][c] = val;
if (val == 1) {
if (r == 0 || r == N - 1 || c == 0 || c == N - 1) continue;
else coreList.push_back(make_pair(r, c));
}
}
}
connectCoreToPower(0, 0, 0);
printf("#%d %d\n", test_case, minWire);
}
return 0;//정상종료시 반드시 0을 리턴해야합니다.
}
Leave a comment