题目大意:连连看,给出每次连线的两个坐标,求能消去多少方块,拐弯最多2次
Sample Input
3 4
1 1 2 2
3 3 4 4
2 2 1 1
6
1 1 1 2
1 3 1 4
2 1 2 2
2 3 2 4
3 1 3 2
3 3 3 4
0 0
Sample Output
12
dfs 代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#pragma warning(disable:4996)
using namespace std;
const int maxn = 550;
int grid[maxn][maxn], di[] = { 0,0,1,-1 }, dj[] = { 1,-1,0,0 }, n, m, p, ti, tj;
bool vis[maxn][maxn];
bool dfs(int ci, int cj, int turns, int curd) {
if (ci == ti && cj == tj && turns <= 2) {
return true;
}
if (turns>2)return false;
for (int i = 0; i<4; ++i) {
int ni = ci + di[i], nj = cj + dj[i];
if (ni >= 0 && ni <= n + 1 && nj >= 0 && nj <= m + 1 && !vis[ni][nj] && (grid[ni][nj] == 0 || ni == ti && nj == tj)) {
vis[ni][nj] = 1;
if (curd != -1 && curd != i) {
if (dfs(ni, nj, turns + 1, i)) {
return true;
}
}
else {
if (dfs(ni, nj, turns, i)) {
return true;
}
}
vis[ni][nj] = 0;
}
}
return false;
}
int main() {
while (scanf("%d%d", &n, &m)) {
if (!n && !m)break;
memset(grid, 0, sizeof(grid));
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
scanf("%d", &grid[i][j]);
}
}
int ans = 0;
scanf("%d", &p);
while (p--) {
int x1, y1, x2, y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
if (grid[x1][y1] && grid[x2][y2] && grid[x1][y1] == grid[x2][y2]) {
ti = x2, tj = y2;
memset(vis, 0, sizeof(vis));
if (dfs(x1, y1, 0, -1)) {
ans += 2;
grid[x1][y1] = grid[x2][y2] = 0;
}
}
}
printf("%d\n", ans);
}
return 0;
}
bfs 代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<iostream>
#pragma warning(disable:4996)
using namespace std;
const int maxn = 1005;
int n, m;
struct node {
int x, y, turn;
};
int a[maxn][maxn];
int vis[maxn][maxn];
int dx[] = { 1,-1,0,0 };
int dy[] = { 0,0,-1,1 };
int xx, yy;
bool bfs(int x, int y, int x1, int y1) {
if (a[x][y] == 0 ||a[x1][y1] == 0 ||a[x1][y1] != a[x][y] || x1 == x && y1 == y)
return false;
queue<node>q;
memset(vis, 0, sizeof(vis));
node now;
now.x = x;
now.y = y;
while (!q.empty()) {
q.pop();
}
now.turn = -1;
q.push(now);
while (!q.empty()) {
now = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
for (int j = 1;; j++) {
node next;
next.x = now.x + dx[i] * j;
next.y = now.y + dy[i] * j;
next.turn = now.turn + 1;
if (next.x<0 || next.x>n + 1 || next.y<0 || next.y>m + 1) {
break;
}
if (a[next.x][next.y]) {
if (next.x == x1 && next.y == y1) {
return true;
}
break;
}
if (vis[next.x][next.y]) {
continue;
}
vis[next.x][next.y] = 1;
if (next.turn < 2) {
q.push(next);
}
}
}
}
return false;
}
int main() {
while (scanf("%d%d", &n, &m) != EOF) {
if (n + m == 0) {
break;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
scanf("%d", &a[i][j]);
}
}
int ans = 0;
int t;
scanf("%d", &t);
while (t--) {
int x, y, x1, y1;
scanf("%d%d%d%d", &x, &y, &x1, &y1);
if (bfs(x, y, x1, y1)) {
ans += 2;
a[x][y] = a[x1][y1] = 0;
}
}
printf("%d\n", ans);
}
return 0;
}