欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

ZOJ 2165 Red and Black

发布时间:2023/12/10 46 豆豆
生活随笔 收集整理的这篇文章主要介绍了 ZOJ 2165 Red and Black 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

1.采用dfs:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
char map[25][25];
int count = 1;
int r,c;
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
bool judge(int x,int y)
{
    if(x<0 || x>= r || y < 0 ||y>=c)
        return 0;
    return 1;
}
void dfs(int x,int y)
{
    map[x][y] = '#';
    int nx = 0;
    int ny = 0;
    for(int i = 0 ; i < 4; i++)
    {
        nx = x + dx[i];
        ny = dy[i] + y;
        if(!judge(nx,ny))
            continue;
        if(map[nx][ny] == '.')
        {
            count++;
            dfs(nx,ny);
        }
    }
}
int main()
{
    //freopen("test.in", "r", stdin);
    while(cin>>c>>r && r&&c)
    {
        count = 1;
        int x0,y0;
        for(int i = 0; i < r; i++ )
        {
            for(int j = 0 ; j < c; j++)
            {
                cin>>map[i][j];
                if(map[i][j] == '@')
                {
                    x0 = i;
                    y0 = j;
                }
            }
        }
        dfs(x0,y0);
        cout<<count<<endl;
    }
    return 0;
}

 

2.bfs:

#include <iostream> #include <queue> using namespace std; structnode { int r; int l;}; int m, n, sr, sl; int dir[2][4] = {{-1, 1, 0, 0}, {0, 0, -1, 1}}; int visited[20][20]; int BFS(); int main() { int i, j; char str[21]; while(cin >> m >> n){ if(m == 0 || n == 0){ break; } for(i = 0; i < n; i++){ cin >> str;for(j = 0; j < m; j++) { if(str[j] == '@'){ sr = i; sl = j; visited[i][j] = 1; } else if(str[j] == '.') {visited[i][j] = 0; } else { visited[i][j] = 1;} } }int count = BFS(); cout << count << endl;} return 0;}int BFS(){ int i, count; queue<node>Q; nodeN, temp; N.r = sr; N.l = sl;count = 1;Q.push(N); while(!Q.empty()){ temp = Q.front();Q.pop();for(i = 0; i < 4; i++){ N = temp; N.r += dir[0][i]; N.l += dir[1][i];if(N.r < 0 || N.r >= n || N.l < 0 || N.l >= m) { continue; } else { if(!visited[N.r][N.l]){ count++;visited[N.r][N.l] = 1;Q.push(N); } }}} return count; }

 

 

转载于:https://www.cnblogs.com/T8023Y/p/3210564.html

总结

以上是生活随笔为你收集整理的ZOJ 2165 Red and Black的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。