美文网首页C++&数据结构与算法
深度优先搜索入门:城堡问题

深度优先搜索入门:城堡问题

作者: cherryleechen | 来源:发表于2017-12-03 20:21 被阅读9次
#include<iostream>
#include<cstring>
#include<stack>

using namespace std;

int R, C; //行数列数
int rooms[51][51];//记录每个方块周围墙状况
int colors[51][51];//记录每个方块的上色序号
int roomNum = 0; //房间数
int roomArea; //房间中所含方块数
int maxRoomArea = 0; //房间所含的最大方块数目

void DFS(int i, int j)
{
//从行号i,列号j的方块开始搜索
    if(colors[i][j]) return;
    colors[i][j] = roomNum;
    roomArea++;
    if((rooms[i][j] & 1) == 0) DFS(i, j - 1);
    if((rooms[i][j] & 2) == 0) DFS(i - 1, j);
    if((rooms[i][j] & 4) == 0) DFS(i, j + 1);
    if((rooms[i][j] & 8) == 0) DFS(i + 1, j);
}

struct Room
{
    int r, c;
    int n;
    Room(int nr, int nc, int nn): r(nr), c(nc), n(nn) {}
    Room() {}
};

void DFSByStack(int r, int c)
{
    stack<Room> st;
    st.push(Room(r, c, rooms[r][c]));
    while(!st.empty())
        {
            Room room = st.top();
            int i, j;
            i = room.r;
            j = room.c;
            if(colors[i][j]) st.pop();
            else
                {
                    colors[i][j] = roomNum;
                    roomArea++;
                    if((rooms[i][j] & 1) == 0)
                        {
                            st.push(Room(i, j - 1, rooms[i][j - 1]));
                        }
                    if((rooms[i][j] & 2) == 0)
                        {
                            st.push(Room(i - 1, j, rooms[i - 1][j]));
                        }
                    if((rooms[i][j] & 4) == 0)
                        {
                            st.push(Room(i, j + 1, rooms[i][j + 1]));
                        }
                    if((rooms[i][j] & 8) == 0)
                        {
                            st.push(Room(i + 1, j, rooms[i + 1][j]));
                        }
                }
        }
}


int main()
{
    cin >> R;
    cin >> C;
    for(int i = 1; i <= R; i++)
        for(int j = 1; j <= C; j++)
            cin >> rooms[i][j];
    memset(colors, 0, sizeof(colors));
    for(int i = 1; i <= R; i++)
        for(int j = 1; j <= C; j++)
            if(colors[i][j] == 0)
                {
                    roomNum++;
                    roomArea = 0;
//                    DFS(i, j);
                    DFSByStack(i, j);
                    maxRoomArea = max(maxRoomArea, roomArea);
                }
    cout << roomNum << endl;
    cout << maxRoomArea << endl;
    for(int i = 1; i <= R; i++)
        {
            for(int j = 1; j <= C; j++)
                cout << colors[i][j] << ' ';
            cout << endl;
        }
}

相关文章

网友评论

    本文标题:深度优先搜索入门:城堡问题

    本文链接:https://www.haomeiwen.com/subject/vzjzbxtx.html