zoj 1002 FireNet

#include <iostream>

using namespace std;

int n, best;
char map[5][5];

bool canPut(int x, int y) {
	if (map[x][y] != '.')
		return false;
	for (int i = x - 1; i >= 0; i--) {
		if (map[i][y] == 'X')
			break;
		if (map[i][y] == 'O')
			return false;
	}
	for (int i = x + 1; i < n; i++) {
		if (map[i][y] == 'X')
			break;
		if (map[i][y] == 'O')
			return false;
	}
	for (int j = y - 1; j >= 0; j--) {
		if (map[x][j] == 'X')
			break;
		if (map[x][j] == 'O')
			return false;
	}
	for (int j = y + 1; j < n; j++) {
		if (map[x][y] == 'X')
			break;
		if (map[x][j] == 'O')
			return false;
	}
	return true;
}

bool donePut() {
	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++)
			if (canPut(i, j))
				return false;
	return true;
}

void search(int m) {
	if (donePut()) {
		best = best < m ? m : best;
		return;
	}
	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++)
			if (canPut(i, j)) {
				map[i][j] = 'O';
				search(m + 1);
				map[i][j] = '.';
			}
}

int main() {
	while ((cin >> n) && n) {
		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++)
				switch (cin.get()) {
				case '.':
					map[i][j] = '.';
					break;
				case 'X':
					map[i][j] = 'X';
					break;
				default:
					j--;
				}
		best = 0;
		search(0);
		cout << best << endl;
	}
	return 0;
}

你可能感兴趣的:(C++,c,C#,J#)