123
返回列表 发新帖
楼主: mhyi
跳转到指定楼层
上一主题 下一主题
收起左侧

Google 12/01 onsite面经

🔗
minggr 2017-1-6 12:45:12 | 只看该作者
全局:
Onsite 1, 一遍BFS
  1. struct point {
  2.     int x, y;

  3.     point(int a, int b): x(a), y(b) {}
  4. };

  5. vector<vector<int>> bfs(vector<vector<char>> &map)
  6. {
  7.     size_t row = map.size();
  8.     size_t col = map[0].size();

  9.     vector<vector<int>> result;
  10.     for (size_t i = 0; i < row; i++)
  11.         result.push_back(vector<int>(col));

  12.     queue<point> q;

  13.     for (size_t i = 0; i < row; i++) {
  14.         for (size_t j = 0; j < col; j++) {
  15.             if (map[i][j] == 'G') {
  16.                 point p(i, j);
  17.                 q.push(p);
  18.                 result[i][j] = -2;
  19.             }
  20.         }
  21.     }

  22.     //up, down, left, right
  23.     vector<vector<int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

  24.     int d = 1;
  25.     while (!q.empty()) {
  26.         size_t size = q.size();
  27.         for (size_t i = 0; i < size; i++) {
  28.             point p = q.front(); q.pop();

  29.             for (auto dir : directions) {
  30.                 int x = p.x + dir[0];
  31.                 int y = p.y + dir[1];

  32.                 if (x >= 0 && x < row && y >= 0 && y < col) {
  33.                     if (map[x][y] == '.') {
  34.                         if (result[x][y] == 0) {
  35.                             result[x][y] = d;
  36.                             q.push(point(x, y));
  37.                         }
  38.                     } else if (map[x][y] == 'L')
  39.                         result[x][y] = -1;
  40.                 }

  41.             }
  42.         }

  43.         d++;
  44.     }

  45.     return result;
  46. }

  47. int main()
  48. {
  49.     vector<vector<char>> map = {
  50.         {'G', 'L', 'L', '.'},
  51.         {'.', '.', 'G', '.'},
  52.         {'L', '.', 'L', '.'},
  53.         {'.', 'G', 'L', 'G'},
  54.         {'.', '.', '.', '.'},
  55.     };

  56.     vector<vector<int>> result = bfs(map);
  57.     for (size_t i = 0; i < result.size(); i++) {
  58.         for (size_t j = 0; j < result[0].size(); j++) {
  59.             cout << result[i][j] << " ";
  60.         }
  61.         cout << endl;
  62.     }

  63.     return 0;
  64. }
复制代码
回复

使用道具 举报

🔗
wajch 2017-2-1 13:46:12 | 只看该作者
全局:
膜一发~~
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表