Amazon classic interview question example details
- 2020-06-01 10:22:20
- OfStack
Amazon interview questions:
In Map as shown below, 0 represents sea water and 1 represents islands, where each island can be connected to the islets in the interval of 8 domains to form an island group. Write the code to count the number of islands in 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
]
*/
Implementation code:
#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++; // found 1 A new land
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;
}
If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!