Cannon
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submission(s): 1062 Accepted Submission(s): 608
An eat action, for example, Cannon A eating chessman B, requires two conditions:
1、A and B is in either the same row or the same column in the chess grid.
2、There is exactly one chessman between A and B.
Here comes the problem.
Given an N x M chess grid, with some existing chessmen on it, you need put maximum cannon pieces into the grid, satisfying that any two cannons are not able to eat each other. It is worth nothing that we only account the cannon pieces you put in the grid, and no two pieces shares the same cell.
In each test case, there are three positive integers N, M and Q (1<= N, M<=5, 0<=Q <= N x M) in the first line, indicating the row number, column number of the grid, and the number of the existing chessmen.
In the second line, there are Q pairs of integers. Each pair of integers X, Y indicates the row index and the column index of the piece. Row indexes are numbered from 0 to N-1, and column indexes are numbered from 0 to M-1. It guarantees no pieces share the same cell.
類似於八皇后,只是把皇后換成了中國象棋的炮,而且棋盤上原先就有一些棋子,問最後最多能放多少個不相互攻擊的炮,數據量很小,直接DFS搜索
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int INF = 0x7fffffff;
int n, m, q, ans;
int mp[10][10];
void dfs(int x, int y, int cnt) {
if (x >= n) {
ans = max(ans, cnt);
return;
}
if (y >= m) {
dfs(x + 1, 0, cnt);
return;
}
if (!mp[x][y]) {
int i;
bool flag = true;
for (i = x - 1; i >= 0 && !mp[i][y]; i--) {}
i--; //因爲炮要隔一個棋子攻擊
for (; i >= 0 && !mp[i][y]; i--) {}
if (i >= 0 && mp[i][y] == 2) flag = false;
if (flag) {
for (i = x + 1; i < n && !mp[i][y]; i++) {}
i++;
for (; i < n && !mp[i][y]; i++) {}
if (i < n && mp[i][y] == 2) flag = false;
}
if (flag) {
for (i = y - 1; i >= 0 && !mp[x][i]; i--) {}
i--;
for (; i >= 0 && !mp[x][i]; i--) {}
if (i >= 0 && mp[x][i] == 2) flag = false;
}
if (flag) {
for (i = y + 1; i < m && !mp[x][i]; i++) {}
i++;
for (; i < m && !mp[x][i]; i++) {}
if (i < m && mp[x][i] == 2) flag = false;
}
if (flag) {
mp[x][y] = 2;
dfs(x, y + 1, cnt + 1); //當前位置放炮
mp[x][y] = 0;
}
}
//當前位置不放炮,此時原因有三種
//1.當前位置有棋子了
//2.當前位置放炮會相互攻擊而不放
//3.故意不放,爲後面DFS放其他棋子騰空間
//但是效果是等價的,都是不放,所以合併爲一條
dfs(x, y + 1, cnt);
}
int main()
{
while (~scanf("%d%d%d", &n, &m, &q)) {
memset(mp, 0, sizeof(mp));
for (int i = 0; i < q; i++) {
int x, y;
scanf("%d%d", &x, &y);
mp[x][y] = 1;
}
ans = -INF;
dfs(0, 0, 0);
printf("%d\n", ans);
}
return 0;
}