模拟类。考虑不周的话会发生Runtime error。
中文题目:
我提交了几次都是Runtime error,看解法觉得没问题。该不会是递归Stack Overflow吧?转念一想才250 * 250的数组,顶多递归这么多次,按理来说不会栈溢出的。
但事实就是栈溢出,为什么呢?试试下面个用例就明白了:
I 5 5 F 1 1 O S output.bmp
我总是抱着最良好的愿望对方不会给我恶意的数据,可惜的是,如果原色和新色相同的话,我的程序就会一直递归下去无穷无尽,于是栈溢出Runtime error。
加一句判断就AC了。
#ifndef ONLINE_JUDGE #pragma warning(disable : 4996) #endif #include <iostream> #include <vector> #include <string> #include <cstring> using namespace std; #define MAX 250 int M, N; char bmp[MAX][MAX]; void print_bmp() { for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) { cout << bmp[j][i]; } cout << endl; } } void fill_pix(const int& x, const int& y, const char& c, const char& nc) { if (bmp[x][y] == c) { bmp[x][y] = nc; if (x - 1 >= 0) { fill_pix(x - 1, y, c, nc); } if (x + 1 < M) { fill_pix(x + 1, y, c, nc); } if (y - 1 >= 0) { fill_pix(x, y - 1, c, nc); } if (y + 1 < N) { fill_pix(x, y + 1, c, nc); } } } ///////////////////////////SubMain////////////////////////////////// int main(int argc, char *argv[]) { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); #endif char cmd; while (cin >> cmd && cmd != 'X') { switch (cmd) { case 'I': { cin >> M >> N; memset(bmp, 'O', sizeof(bmp)); }break; case 'C': { memset(bmp, 'O', sizeof(bmp)); }break; case 'L': { int X, Y; char C; cin >> X >> Y >> C; --X, --Y; bmp[X][Y] = C; }break; case 'V': { int X, Y1, Y2; char C; cin >> X >> Y1 >> Y2 >> C; if (X > M || Y1 > N || Y2 > N) { break; } --X, --Y1, --Y2; if (Y1 > Y2) { swap(Y1, Y2); } for (int i = Y1; i <= Y2; ++i) { bmp[X][i] = C; } }break; case 'H': { int Y, X1, X2; char C; cin >> X1 >> X2 >> Y >> C; if (X1 > M || X2 > M || Y > N) { break; } --Y, --X1, --X2; if (X1 > X2) { swap(X1, X2); } for (int i = X1; i <= X2; ++i) { bmp[i][Y] = C; } }break; case 'K': { int X1, X2, Y1, Y2; char C; cin >> X1 >> Y1 >> X2 >> Y2 >> C; if (X1 > M || X2 > M || Y1 > N || Y2 > N) { break; } --X1, --X2, --Y1, --Y2; if (X1 > X2) { swap(X1, X2); } if (Y1 > Y2) { swap(Y1, Y2); } for (int i = X1; i <= X2; ++i) { for (int j = Y1; j <= Y2; ++j) { bmp[i][j] = C; } } }break; case 'F': { int X, Y; char C; cin >> X >> Y >> C; if (X > M || Y > N) { break; } --X, --Y; char oc = bmp[X][Y]; if (oc == C) { break; } fill_pix(X, Y, oc, C); }break; case 'S': { string NAME; cin >> NAME; cout << NAME << endl; print_bmp(); }break; default: { }break; } } #ifndef ONLINE_JUDGE fclose(stdin); fclose(stdout); system("out.txt"); #endif return 0; } ///////////////////////////End Sub//////////////////////////////////