33,009
社区成员
发帖
与我相关
我的任务
分享
struct SearchBuild
{
SearchBuild(unsigned char x, unsigned char y, unsigned char w, unsigned char h)
: m_x(x), m_y(y), m_w(w), m_h(h)
{};
unsigned char m_x, m_y, m_w, m_h;
};
struct SearchNode
{
SearchNode() : m_grids(GRIDMAXCOUNT * GRIDMAXCOUNT) {};
std::vector<bool> m_grids;
std::vector<SearchBuild> m_builds;
unsigned char m_x;
unsigned char m_y;
unsigned short m_wasteSpace;
bool operator<(const SearchNode& rhs) const
{
int myw = m_wasteSpace;
int hew = rhs.m_wasteSpace;
if(myw < hew)
{
return true;
}
else if(myw > hew)
{
return false;
}
else
{
return m_builds.size() > rhs.m_builds.size();
}
}
bool IsFull()
{
return m_y >= GRIDMAXCOUNT;
}
bool NextPoint()
{
++m_x;
while(true)
{
if(m_x >= GRIDMAXCOUNT)
{
m_x = 0;
++m_y;
continue;
}
if(m_y >= GRIDMAXCOUNT)
{
return false;
}
if(m_grids[m_y * GRIDMAXCOUNT + m_x])
{
return true;
}
else
{
++m_x;
}
}
return false;
}
bool HaveSpace(int width, int height)
{
for(int i = m_x; i < m_x + width; ++i)
{
for(int j = m_y; j < m_y + height; ++j)
{
if(!m_grids[j * GRIDMAXCOUNT + i])
return false;
}
}
return true;
}
void AddBuild(int width, int height)
{
for(int i = m_x; i < m_x + width; ++i)
{
for(int j = m_y; j < m_y + height; ++j)
{
m_grids[j * GRIDMAXCOUNT + i] = false;
}
}
m_builds.push_back(SearchBuild(m_x, m_y, width, height));
}
};
void CTestDlg::OnBnClickedButton1()
{
std::multiset<SearchNode> searchTable;
SearchNode node;
SearchNode newNode;
node.m_x = 0;
node.m_y = 0;
node.m_wasteSpace = 0;
// 下面这段是读入 100 * 100 的区域数据,不用管它
const GridVector& vec = mc_SceneShow.GetGridVec();
for(int x = 0; x < GRIDMAXCOUNT; ++x)
{
for(int y = 0; y < GRIDMAXCOUNT; ++y)
{
if(vec[x][y] == GT_TOBUILD)
node.m_grids[y * GRIDMAXCOUNT + x] = true;
else
node.m_grids[y * GRIDMAXCOUNT + x] = false;
}
}
searchTable.insert(node);
while(!searchTable.empty())
{
node = *searchTable.begin();
searchTable.erase(searchTable.begin());
if(node.IsFull())
{
break;
}
if(node.HaveSpace(5, 4))
{
newNode = node;
newNode.AddBuild(5, 4);
newNode.NextPoint();
searchTable.insert(newNode);
}
if(node.HaveSpace(2, 3))
{
newNode = node;
newNode.AddBuild(2, 3);
newNode.NextPoint();
searchTable.insert(newNode);
}
if(node.HaveSpace(3, 2))
{
newNode = node;
newNode.AddBuild(3, 2);
newNode.NextPoint();
searchTable.insert(newNode);
}
node.NextPoint();
node.m_wasteSpace++;
searchTable.insert(node);
}
// 下面是显示搜索结果,也不用管它
for(size_t i = 0; i < node.m_builds.size(); ++i)
{
mc_SceneShow.AddBuild(node.m_builds[i].m_x, node.m_builds[i].m_y, node.m_builds[i].m_w, node.m_builds[i].m_h);
}
mc_SceneShow.Invalidate(TRUE);
}