您的位置:首页 > 其它

用深搜和广搜两种方法解题---黑色格子

2016-04-24 23:49 232 查看
给一个字符矩阵,“.”代表黑色格子,“#”代表红色格子,有一个起点“@”,它属于黑色格子,一个人从起点出发,只能走黑色格子,并且只能上下左右走,不能对角线走,问这个人能走到的黑色格子有多少个。输出个数。输入W,H,代表有W列,H行,然后输入一个字符矩阵,输出能走到的最多的黑色格子的个数,包括起点。
 广度优先搜索:

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
int num;
char map[25][25];
int visited[25][25];
int dir[4][2] = {0, -1, 1, 0, 0, 1, -1, 0};
void DFS(int x, int y, int n, int m)
{
  int mx, my;
  for(int i = 0; i<4; i++)
  {
    mx = x+dir[i][0];
my = y+dir[i][1];

    if(mx>=1 && mx<=n && my>=1 && my<=m && !visited[mx][my] && map[mx][my]=='.')
    {
      visited[mx][my] = 1;
      num++;
      DFS(mx, my, n, m);
    }
  }
}
 
int main()
{
  int n, m, x, y;
  while(scanf("%d%d", &m, &n)!=EOF && (n || m))
  {
    num = 1;
    memset(visited, 0, sizeof(visited));
    for(int i = 1; i<=n; i++)
    {
      for(int j = 1; j<=m; j++)
      {
        cin>>map[i][j];
        if(map[i][j] == '@')
        {
          x = i;
          y = j;
          visited[x][y] = 1;
        }
      }
    }
 
    DFS(x, y, n, m);
 
4000
   printf("%d\n", num);

  }
 
  return 0;
}
深度优先搜索:

#include <stdio.h>
#include <queue>
using namespace std;
#define MAXN 25
bool vis[MAXN][MAXN];
char map[MAXN][MAXN];
int W, H, result, dx[4] = {1, 0, -1, 0}, dy[4] = {0, -1, 0, 1};
struct Tile { //
以状态(棋子坐标)为结点

    int x, y;
}tile[MAXN*MAXN];
queue <Tile> q;
bool reachable(Tile next)
{
    return map[next.x][next.y] != '#' && next.x >= 1 && next.x <= W && next.y >= 1 && next.y <= H;
}
void bfs()
{
    Tile cur, next;
    while (!q.empty())
    {
        cur = q.front();
        q.pop();
        result++;
        for (int i = 0; i < 4; ++i)
       {
            next.x = cur.x + dx[i];
            next.y = cur.y + dy[i];
            if (reachable(next) && !vis[next.x][next.y])
            {
               vis[next.x][next.y] = true;
               q.push(next);
            }
        }
    }
}
int main()
{
    int i, j;
    Tile start;
    while (scanf("%d%d", &W, &H), W && H)
    {
        result = 0;
        memset(vis, false, sizeof(vis)); //
数据初始化

        for (i = 1; i <= H; ++i)
            for (j = 1; j <= W; ++j)
            {
                scanf(" %c", &map[j][i]); // x y
                if (map[j][i] == '@')
                {
                    start.x = j;
                    start.y = i;
                    vis[j][i] = true;
                    q.push(start);
                }
            }  
        bfs();
        printf("%d\n", result);
    }
    return 0;
}





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: