代码
时间: 2023-07-02 16:14:21 浏览: 32
以下是C++的代码实现:
```c++
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 1010;
int n, sx, sy, tx, ty;
int g[N][N]; // 海洋地图
int d[N][N]; // 距离数组
int dx[4] = {-1, 0, 1, 0}; // 四个方向
int dy[4] = {0, 1, 0, -1};
void bfs() {
queue<pair<int, int>> q;
q.push({sx, sy}); // 将起点加入队列中
memset(d, -1, sizeof d);
d[sx][sy] = 0;
while (!q.empty()) {
auto t = q.front();
q.pop();
int x = t.first, y = t.second;
if (x == tx && y == ty) return; // 找到铁塔尼号,直接返回
for (int i = 0; i < 4; i++) { // 枚举四个方向
int a = x + dx[i], b = y + dy[i];
if (a < 0 || a >= n || b < 0 || b >= n || g[a][b] == 1 || d[a][b] != -1) continue; // 越界或者是陆地或者已经访问过了,直接跳过
d[a][b] = d[x][y] + 1;
q.push({a, b});
}
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> g[i][j];
cin >> sx >> sy >> tx >> ty;
bfs();
cout << d[tx][ty] << endl;
return 0;
}
```
时间复杂度为O(n^2),空间复杂度也为O(n^2)。