AcWing 756. 蛇形矩阵
原题链接
简单
作者:
Jiang锋时刻
,
2021-01-28 21:33:23
,
所有人可见
,
阅读 240
算法1
Java 代码
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int[][] res = new int[m][n];
int left = 0, right = n - 1, top = 0, bottom = m - 1;
int num = 1;
while(num <= m * n) {
for(int i = left; i <= right && num <= m * n; i++) {
res[top][i] = num++;
}
top++;
for(int i = top; i <= bottom && num <= m * n; i++) {
res[i][right] = num++;
}
right--;
for(int i = right; i >= left && num <= m * n; i--) {
res[bottom][i] = num++;
}
bottom--;
for(int i = bottom; i >= top && num <= m * n; i--) {
res[i][left] = num++;
}
left++;
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
System.out.print(res[i][j] + " ");
}
System.out.println();
}
}
}
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int col = sc.nextInt();
int res[][] = new int[row][col];
int[] dx = new int[]{-1, 0, 1, 0};
int[] dy = new int[]{0, 1, 0, -1};
int x = 0, y = 0, d = 1;
for(int num =1; num <= row * col; num++) {
res[x][y] = num;
int next_x = x + dx[d];
int next_y = y + dy[d];
if(next_x < 0 || next_x >= row || next_y < 0 || next_y >= col || res[next_x][next_y] != 0) {
d = (d + 1) % 4;
next_x = x + dx[d];
next_y = y + dy[d];
}
x = next_x;
y = next_y;
}
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
System.out.print(res[i][j] + " ");
}
System.out.println();
}
}
}