百度之星初赛(2)—BFS小试牛刀 problem 1002 占领棋盘

来源:互联网 发布:软件二次开发申请专利 编辑:程序博客网 时间:2024/06/06 05:15


//利用队列实现宽度优先搜索算法。

//其中,本题转换思维,若被占领的城市的对角有城市 即2x2的方格内,其余两个城市被占领,被占领的城市入队,当队列为空时就得到的解,宽度优先搜索算法

#include <iostream>
#include <vector>
#include <queue>
#include <set>
using namespace std;
const int n_max = 500;
const int m_max = 500;
int m, n;
int a[n_max][m_max];
const int dx[4] = { -1, -1, 1, 1 };
const int dy[4] = { -1, 1, 1, -1 };
queue<pair<int, int>> s;
int main()
{
 int GetOccupynum(int x, int y);
 
 int T = 0;

 cin >> T;

 
 for (int i = 0; i < T; i++)
 {
  int count = 0;
  
  cin >> n >> m;
  int g;
  cin >> g;
  for (int i = 1; i < n + 1; i++)
  {
   for (int j = 1; j < m + 1; j++)
    a[i][j] = 0;
  }
  memset(a, 0, sizeof (a));

  for (int i = 0; i < g; i++)
  {
   pair<int, int> p;
   cin >>p.first>>p.second;
   a[p.first][p.second] = 1;
   s.push(p);
      
  }
  while (!s.empty())
  {
   int x = s.front().first;
   int y = s.front().second;
   s.pop();
   count+=GetOccupynum(x, y);
  }
  
  cout << "Case #" << i + 1 <<":"<< "\n" << count + g << endl;
  count = 0;
 }

 system("pause");
 return 0;
}
int GetOccupynum(int x, int y)
{
 int cnt = 0;
 for (int i = 0; i < 4; i++)
 {
  int temp_x = x + dx[i];
  int temp_y = y + dy[i];
  if ((0 < temp_x < n + 1) && (0 < temp_y < m + 1))
  {
   if (a[temp_x][temp_y] == 1)
   {
    if (a[temp_x][y] == 0)
    {
     a[temp_x][y] = 1;
     cnt++;
     s.push(make_pair(temp_x, y));
    }
    if (a[x][temp_y] == 0)
    {
     a[x][temp_y] = 1;
     cnt++;
     s.push(make_pair(x, temp_y));
    }

   }
  }
  else
  {
   continue;
  }
  
 }
 return cnt;
}
//void solve1()
//{
// const int n_max = 500;
// const int m_max = 500;
// int a[n_max + 1][m_max + 1] = { 0 };
// int di[4] = { -1, 0, 1, 0 };
// int T = 0;
// cin >> T;
// for (int i = 0; i < T; i++)
// {
//  int m, n;
//  cin >> m >> n;
//  int g;
//  cin >> g;
//  for (int i = 0; i < g; i++)
//  {
//   int x, y;
//   cin >> x >> y;
//   a[x][y] = 1;
//
//  }
//  int g_other = 0;
//  int flag = 0;
//  for (int i = 1; i < m + 1; i++)
//  {
//
//   for (int j = 1; j < n + 1; j++)
//   {
//
//    if (a[i][j] == 0)
//    {
//     for (int k = 0; k < 4; k++)
//     {
//
//      if (0 < (i + di[k]) <= m && 0 < j + di[3 - k] <= n)
//      {
//       if (a[i + di[k]][j + di[3 - k]] == 1)
//        flag++;
//      }
//     }
//     if (flag > 2)
//      g_other++;
//     if (flag == 2)
//     {
//      if ((a[i + 1][j] == 1 && a[i - 1][j] == 1) || (a[i][j + 1] == 1 && a[i][j - 1] == 1))
//       flag = 0;
//      else
//       g_other++;
//
//     }
//     flag = 0;
//
//    }
//   }
//
//  }
//  cout << "Case #" << i + 1 << endl;
//  cout << g_other + g << endl;
//
//
// }
//}

0 0