DivI lev2
定義grid,0為空白,1代表有障礙或已考慮
從每個格式開始flood fill一遍,記錄flood fill的格子數量
#include <iostream><br />#include <queue><br />#include <vector><br />#include <cstring><br />#include <sstream><br />#include <algorithm></p><p>#define HEIGHT400<br />#define WIDTH600</p><p>using namespace std;</p><p>typedef struct pixel {<br />int x;<br />int y;<br />} pixel;</p><p>const int xoffset[4] = {1, 0, -1, 0};<br />const int yoffset[4] = {0, 1, 0, -1};</p><p>class grafixMask {<br />private:<br />vector<int>holes;<br />int grid[HEIGHT][WIDTH];</p><p>intisValid(pixel n)<br /> {<br />if (n.x < 0 || n.x > HEIGHT - 1 || n.y < 0 || n.y > WIDTH - 1<br />|| grid[n.x][n.y])<br />return 0;</p><p>return 1;<br />}</p><p>public:<br />vector<int> sortedAreas(vector<string> rectangles)<br />{<br />memset(grid, 0, sizeof(int) * HEIGHT * WIDTH);</p><p>for (int i = 0; i < rectangles.size(); i++) {<br />istringstream ss(rectangles[i]);<br />int tlx, tly, brx, bry;<br />ss >> tlx >> tly >> brx >> bry;<br />for (int x = tlx; x <= brx; x++)<br />for (int y = tly; y <= bry; y++)<br />grid[x][y] = 1;<br />}</p><p>for (int x = 0; x < HEIGHT; x++)<br />for (int y = 0; y < WIDTH; y++) {<br />if (grid[x][y] == 1)<br />continue;<br />//cout << "x = " << x << " y = " << y << endl;<br />queue<pixel> q;<br />int cnt = 1;<br />pixel p;<br />p.x = x;<br />p.y = y;<br />grid[x][y] = 1;<br />q.push(p);</p><p>while (!q.empty()) {<br />p = q.front();<br />q.pop();<br />pixel newp;<br />for (int i = 0; i < 4; i++) {<br />newp.x = p.x + xoffset[i];<br />newp.y = p.y + yoffset[i];</p><p>if (isValid(newp)) {<br />cnt++;<br />//cerr << cnt << endl;<br />grid[newp.x][newp.y] = 1;<br />q.push(newp);<br />}<br />}<br />}<br />holes.push_back(cnt);<br />}<br />sort(holes.begin(), holes.end());<br />return holes;<br />}<br />};</p><p>int main()<br />{<br />grafixMask gm;</p><p>// example 0<br />cout << "example 0: " << endl;<br />vector<string> vec;<br />vec.push_back("0 292 399 307");</p><p>vec.push_back("0 292 399 307");<br />vector<int>res = gm.sortedAreas(vec);</p><p>return 0;<br />}<br />