[Coursera]演算法基礎_Week2_列舉_Q1

yiliu_cr發表於2015-12-13
#include <iostream>
using namespace std;
#define INF 1000000
int opn = 0;
void Op(int n, char wall[16][16], int op[16]) {
	for (int i = 1; i <= n; i++) {
		if (op[i] == 1) {
			opn++;
			if (wall[1][i] == 'y')
				wall[1][i] = 'w';
			else
				wall[1][i] = 'y';
			if (wall[1][i - 1] == 'y')
				wall[1][i - 1] = 'w';
			else
				wall[1][i - 1] = 'y';
			if (wall[1][i + 1] == 'y')
				wall[1][i + 1] = 'w';
			else
				wall[1][i + 1] = 'y';
			if (wall[2][i] == 'y')
				wall[2][i] = 'w';
			else
				wall[2][i] = 'y';
		}
	}
	for (int i = 2; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			if (wall[i - 1][j] == 'w') {
				opn++;
				wall[i - 1][j] = 'y';
				if (wall[i][j] == 'y')
					wall[i][j] = 'w';
				else
					wall[i][j] = 'y';
				if (wall[i][j - 1] == 'y')
					wall[i][j - 1] = 'w';
				else
					wall[i][j - 1] = 'y';
				if (wall[i][j + 1] == 'y')
					wall[i][j + 1] = 'w';
				else
					wall[i][j + 1] = 'y';
				if (wall[i + 1][j] == 'y')
					wall[i + 1][j] = 'w';
				else
					wall[i + 1][j] = 'y';
			}
		}
	}
}
int main() {
	int t;
	cin >> t;
	while (t--) {
		char wall[16][16] = { '\0' };
		int op[16];
		int n;
		cin >> n;
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= n; j++) {
				cin >> wall[i][j];
			}
		}
		int z = 1;
		for (int i = 0; i < n; i++)
			z *= 2;
		int *p = new int[z];
		int Z = z;
		while(z--) {
			char temp[16][16] = { '\0' };
			for (int i = 1; i <= n; i++) {
				for (int j = 1; j <= n; j++) {
					temp[i][j] = wall[i][j];
				}
			}
			int t = z;
			for (int i = 1; i <= n; i++) {
				op[i] = t % 2;
				t /= 2;
			}
			Op(n, temp, op);
			int f = 1;
			for (int i = 1; i <= n; i++) {
				if (temp[n][i] == 'w')
					f = 0;
			}
			if (f)
				p[z] = opn;
			else
				p[z] = INF;
			opn = 0;
		}
		int res = INF;
		for (int i = 0; i < Z; i++) {
			if (res > p[i])
				res = p[i];
		}
		if (res == INF)
			cout << "inf" << endl;
		else
			cout << res << endl;
		delete []p;
	}
	return 0;
}

相關文章