Спираль самая
user_7290026
java
2 years ago
2.0 kB
9
Indexable
package yulalenk.exam.io;
import java.util.Scanner;
public class SpiralMatrix {
private static void spiralFill(char[][] matrix, String inputString) {
int[] directionsX = {0, 1, 0, -1};
int[] directionsY = {1, 0, -1, 0};
int rows = matrix.length;
int cols = matrix[0].length;
int totalElements = rows * cols;
int row = 0, col = 0;
int directionIndex = 0;
int stringIndex = 0;
while (stringIndex < inputString.length()) {
if (row >= 0 && row < rows && col >= 0 && col < cols && matrix[row][col] == 0) {
matrix[row][col] = inputString.charAt(stringIndex);
stringIndex++;
}
int newRow = row + directionsX[directionIndex];
int newCol = col + directionsY[directionIndex];
if (newRow < 0 || newRow >= rows || newCol < 0 || newCol >= cols || matrix[newRow][newCol] != 0) {
directionIndex = (directionIndex + 1) % 4;
}
row += directionsX[directionIndex];
col += directionsY[directionIndex];
}
}
private static char[][] spiralMatrix(String inputString, int rows, int cols) {
char[][] matrix = new char[rows][cols];
spiralFill(matrix, inputString.substring(0, Math.min(rows * cols, inputString.length())));
return matrix;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] numbers = scanner.nextLine().split(" ");
int rows = Integer.parseInt(numbers[0]);
int cols = Integer.parseInt(numbers[1]);
String inputString = scanner.nextLine();
char[][] matrix = spiralMatrix(inputString, rows, cols);
StringBuilder stringBuilder = new StringBuilder();
for (char[] row : matrix) {
for (char cell : row) {
stringBuilder.append(cell == 0 ? "" : cell);
}
}
System.out.println(stringBuilder);
}
}Editor is loading...