Page List

Search on the blog

2010年9月2日木曜日

2次元座標処理Tips

2次元平面上で何かをするような問題はよくある。
コンピュータ上で、実装する場合は、だいたい2次元配列を用意して処理をする。x[i][j]を座標(i, j)とみなして2次元平面を表現するわけだ。

例えば、”8個の接している点の中で自身と同じ値を持っているものの個数を数える”とか”上下左右の接している4点のみ移動できる時○○せよ。”なんて問題はよく見かける。
私も数問解いた記憶がある。。。

しかし、どうも上手く実装できない。
何故かコードが長くなってしまう。
関数化できない。。

こんなヘタレな悩みが昨日解決された。やっぱり人のソースコードを見るのは大事ですね。。

例によって、PKUの問題で説明します。
今回の問題は、Red and Black。まあよくある問題です。

で、これが私が書いたヘタレコード。。笑


class Plot {
public:
int x;
int y;
Plot(int x, int y) {
this->x = x;
this->y = y;
}

};

int main() {
int w, h;
for (;;) {
cin >> w >> h;
if (!w && !h)
break;

VS tiles;
REP(i, h) {
string tileLine;
char c;
REP(j, w) {
cin >> c;
tileLine += c;
}
tiles.PB(tileLine);
}

queue<Plot> prc;
REP(i, h) {
REP(j, w) {
if (tiles[i][j] == '@') {
prc.push(Plot(i, j));
break;
}
}
}

int ret = 0;
bool done[h][w];
memset(done, 0, sizeof(done));

while (prc.size()) {
int x = prc.front().x;
int y = prc.front().y;
prc.pop();
++ret;

if (x > 0) {
if (tiles[x - 1][y] == '.' && !done[x - 1][y]) {
prc.push(Plot(x - 1, y));
done[x - 1][y] = true;
}
}
if (x < h - 1) {
if (tiles[x + 1][y] == '.' && !done[x + 1][y]) {
prc.push(Plot(x + 1, y));
done[x + 1][y] = true;
}
}
if (y > 0) {
if (tiles[x][y - 1] == '.' && !done[x][y - 1]) {
prc.push(Plot(x, y - 1));
done[x][y - 1] = true;
}
}
if (y < w - 1) {
if (tiles[x][y + 1] == '.' && !done[x][y + 1]) {
prc.push(Plot(x, y + 1));
done[x][y + 1] = true;
}
}
}
cout << ret << endl;
}

return 0;
}
なんとか、4つの方向に同様の処理をしている部分を関数化したかったが、関数化するにも、2次元配列使っているので面倒臭いことになるなと考えて挫折。。。
で、他の人のソース見てたら、シンプルな方法があったので、頂きました。。(ごちそうさま。)

こんな感じ。


const int dx[] = { -1, 1, 0, 0 };
const int dy[] = { 0, 0, -1, 1 };

int main() {
int w, h;
for (;;) {
cin >> w >> h;
if (!w && !h)
break;

VS tiles;
REP(i, h) {
string tileLine;
char c;
REP(j, w) {
cin >> c;
tileLine += c;
}
tiles.PB(tileLine);
}

queue<Plot> prc;
REP(i, h) {
REP(j, w) {
if (tiles[i][j] == '@') {
prc.push(Plot(i, j));
break;
}
}
}

int ret = 0;
bool done[h][w];
memset(done, 0, sizeof(done));

while (prc.size()) {
int x = prc.front().x;
int y = prc.front().y;
prc.pop();
++ret;
REP(i, 4) {
int xx = x + dx[i];
int yy = y + dy[i];

if (xx < 0 || xx > h - 1 || yy < 0 || yy > w - 1)
continue;
if (tiles[xx][yy] == '.' && !done[xx][yy]) {
prc.push(Plot(xx, yy));
done[xx][yy] = true;
}
}
}
cout << ret << endl;
}

return 0;
}
いや、だいぶシンプル。
始めに、変化量を予め定数の配列で確保しておけばいいですね!!ここでポイントは、2次元方向の変化量を次元毎に個別に持たせて2重ループで回そうって考えないことです。変化パターンをまとめて書きだして、それぞれのx変化量、y変化量を配列dx, dyに格納しましょう。

0 件のコメント:

コメントを投稿