【HDOJ】3295 An interesting mobile game

时间:2021-09-05 20:44:51

其实就是一道搜索模拟题。因为数据量小,用char就够了。

 /* 3295 */
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
using namespace std; typedef struct {
char m[][];
char x, y;
char s, c;
} node_t; typedef struct subNode_t {
char x, y;
subNode_t() {}
subNode_t(char xx, char yy) {
x = xx; y = yy;
}
} subNode_t; bool visit[][];
node_t beg, cur;
int n, m, cnt;
char dir[][] = {
-,,,-,,,,
};
queue<node_t> Q;
queue<subNode_t> q; inline bool check(char x, char y) {
return x< || x>=n || y< || y>=m;
} void remove(char x, char y, char cl) {
char i, j, k;
subNode_t nd; ++cur.s;
cur.m[x][y] = ;
visit[x][y] = true;
--cur.c;
q.push(subNode_t(x, y)); while (!q.empty()) {
nd = q.front();
q.pop();
for (i=; i<; ++i) {
x = nd.x + dir[i][];
y = nd.y + dir[i][];
if (check(x, y) || visit[x][y])
continue;
if (cur.m[x][y] == cl) {
cur.m[x][y] = ;
visit[x][y] = true;
--cur.c;
q.push(subNode_t(x, y));
}
}
}
} node_t shift() {
char i, j, k, r;
bool flag;
node_t nd; // copy from cur
nd.s = cur.s;
nd.c = cur.c;
nd.x = cur.x;
nd.y = cur.y;
memset(nd.m, , sizeof(nd.m)); // fall down
r = ;
for (j=; j<m; ++j) {
k = n-;
for (i=n-; i>=; --i)
if (cur.m[i][j])
nd.m[k--][r] = cur.m[i][j];
if (k < n-)
++r;
} return nd;
} char bfs() {
char i, j, k;
node_t nd; while (!Q.empty())
Q.pop(); memset(visit, false, sizeof(visit));
for (i=; i<n; ++i) {
for (j=; j<n; ++j) {
if (beg.m[i][j] && !visit[i][j]) {
cur = beg;
remove(i, j, beg.m[i][j]);
nd = shift();
Q.push(nd);
}
}
} while (!Q.empty()) {
beg = Q.front();
Q.pop();
if (beg.c == )
return beg.s;
memset(visit, false, sizeof(visit));
for (i=; i<n; ++i) {
for (j=; j<m; ++j) {
if (beg.m[i][j] && !visit[i][j]) {
cur = beg;
remove(i, j, beg.m[i][j]);
nd = shift();
Q.push(nd);
}
}
}
} return ;
} int main() {
int i, j, k; #ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
#endif while (scanf("%d%d",&n,&m) != EOF) {
cnt = ;
beg.s = ;
for (i=; i<n; ++i) {
for (j=; j<m; ++j) {
scanf("%d", &k);
beg.m[i][j] = k;
if (k)
++cnt;
}
}
beg.c = cnt;
k = bfs();
printf("%d\n", k);
} return ;
}