AcWing 756. Java - 蛇形矩阵
原题链接
困难
作者:
熊本熊本熊
,
2019-05-05 10:46:53
,
所有人可见
,
阅读 1583
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Main solution = new Main();
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
int m = reader.nextInt();
int[][] ans = solution.python_matrix(n, m);
for(int i =0; i < n; i++){
for(int j = 0; j < m; j++){
System.out.print(ans[i][j]);
System.out.print(" ");
}
System.out.print("\n");
}
}
public int[][] python_matrix(int m, int n){
int[][] ans = new int[m][n];
boolean[][] used = new boolean[m][n];
int[] dx = {0, 1, 0, -1};
int[] dy = {1, 0, -1, 0};
int num = 1;
int x = 0;
int y = 0;
int direction_index = 0;
while (num <= m*n){
ans[x][y] = num;
used[x][y] = true;
num++;
x += dx[direction_index];
y += dy[direction_index];
if(x < 0 || x >= m || y <0 || y >= n || used[x][y]){
x -= dx[direction_index];
y -= dy[direction_index];
direction_index ++;
direction_index %= 4;
x += dx[direction_index];
y += dy[direction_index];
}
}
return ans;
}
}
感觉这道题应该是中等难度,不能算Hard
这道题的标签是语法题hh
在语法题里算Hard~