亚马逊面试题

时间:2022-05-03
本文章向大家介绍亚马逊面试题,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

如下所示的Map中,0代表海水,1代表岛屿,其中每一个岛屿与其八领域的区间的小岛能相连组成岛屿群。写代码,统计Map中岛屿个数。

/* Q1. Map [ 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 ] */

先直接上代码,后续等我有时间再写解题报告。

#include<iostream>#include<queue>using namespace std;typedef struct {  int i;  int j;
}position;void search(int a[][], int n, int i, int j, int cnt) {    queue<position> qu = new queue<position>();

    position p;
    p.i = i;
    p.j = j;

    qu.push(p);
    a[i][j] = cnt;    while (!qu.empty()) {
        p = qu.pop();                 for (int ii = p.i - 1; ii <= p.i + 1; ii++) {         for (int jj = p.j - 1; jj <= p.j + 1; jj++) {                if (ii >= 0 && ii < n && jj >= 0 && jj < n && a[ii][jj] == 1 && (ii != i || jj != j)) {
          a[ii][jj] = cnt;
          p.i = ii;
          p.j = jj;
          qu.push(p);
         }
       }
    }
   }
}int count(int a[][], int n) {        int cnt = 1;        for (int i = 0; i < n; i++) {               for (int j = 0; j < n; j++) {                        if (a[i][j] == 1) {
          cnt++; // 发现一个新陆地
          search(a, n, i, j, cnt);
        }
     }
   }       return cnt;
}int main() {        int n;        cin >> n;        int a[][] = new int[n][n];        for (int i = 0; i < n; i++) {               for (int j = 0; j < n; j++) {                      cin >> a[i][j];
        }
    }         int cnt = count(a, n);         cout << cnt - 1 << endl;              return 0;
}