import java.util.Arrays; import java.util.LinkedList; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Integer[] arr = Arrays.stream(sc.nextLine().split(",")).map(Integer::parseInt).toArray(Integer[]::new); System.out.println(getResult(arr)); } public static int getResult(Integer[] arr) { int n = (int) Math.sqrt(arr.length); int[][] matrix = new int[n][n]; LinkedList<Integer[]> queue = new LinkedList<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrix[i][j] = arr[i * n + j]; if (matrix[i][j] == 1) queue.add(new Integer[] {i, j}); } } if (queue.size() == 0 || queue.size() == arr.length) { return -1; } int healthy = arr.length - queue.size(); int[][] offsets = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int day = 0; while (queue.size() > 0 && healthy > 0) { LinkedList<Integer[]> newQue = new LinkedList<>(); for (Integer[] tmp : queue) { int x = tmp[0], y = tmp[1]; for (int[] offset : offsets) { int newX = x + offset[0]; int newY = y + offset[1]; if (newX >= 0 && newX < n && newY >= 0 && newY < n && matrix[newX][newY] == 0) { matrix[newX][newY] = 1; healthy--; newQue.add(new Integer[] {newX, newY}); } } } day++; queue = newQue; } return day; } }翻译成C++
时间: 2024-04-17 10:26:19 浏览: 18
以下是将给定的Java代码翻译为C++的版本:
```cpp
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
int getResult(vector<int>& arr) {
int n = sqrt(arr.size());
vector<vector<int>> matrix(n, vector<int>(n));
queue<pair<int, int>> q;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = arr[i * n + j];
if (matrix[i][j] == 1) {
q.push({i, j});
}
}
}
if (q.empty() || q.size() == arr.size()) {
return -1;
}
int healthy = arr.size() - q.size();
vector<vector<int>> offsets = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int day = 0;
while (!q.empty() && healthy > 0) {
queue<pair<int, int>> newQ;
while (!q.empty()) {
pair<int, int> tmp = q.front();
q.pop();
int x = tmp.first, y = tmp.second;
for (vector<int>& offset : offsets) {
int newX = x + offset[0];
int newY = y + offset[1];
if (newX >= 0 && newX < n && newY >= 0 && newY < n && matrix[newX][newY] == 0) {
matrix[newX][newY] = 1;
healthy--;
newQ.push({newX, newY});
}
}
}
day++;
q = newQ;
}
return day;
}
int main() {
string input;
getline(cin, input);
vector<int> arr;
size_t pos = 0;
while ((pos = input.find(',')) != string::npos) {
arr.push_back(stoi(input.substr(0, pos)));
input.erase(0, pos + 1);
}
arr.push_back(stoi(input));
cout << getResult(arr) << endl;
return 0;
}
```
请注意,上述代码只是翻译了给定的Java代码,并进行了一些必要的语法和数据结构的更改。如果您在使用时遇到任何问题,请提供更多信息以便我可以帮助您解决。