Spiral Matrix
程序员文章站
2022-07-12 09:29:57
...
题目
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
答案
class Solution {
private boolean valid(int[][] matrix, boolean[][] visited, int x, int y) {
return x >= 0 && x < matrix.length && y>= 0 && y < matrix[0].length && visited[x][y] == false;
}
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<>();
if(matrix.length == 0) return list;
int m = matrix.length, n = matrix[0].length;
boolean[][] visited = new boolean[m][n];
int[][] dxdy = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
// go right, down, left, top. Change directions when hit a visited position
int x = 0, y = -1, tx = 0, ty = 0;
int cnt = 0, dir = 0;
while(cnt < m * n) {
tx = x + dxdy[dir][0];
ty = y + dxdy[dir][1];
if(valid(matrix, visited, tx, ty)) {
x = tx;
y = ty;
}
else {
dir = (dir + 1) % 4;
continue;
}
list.add(matrix[x][y]);
visited[x][y] = true;
cnt++;
}
return list;
}
}
上一篇: 剑指Offer算法
下一篇: 【算法】剑指offer-数组
推荐阅读
-
Matrix AI (MAN)人工智能生态平台赋能智能医疗
-
如何使用Matrix对bitmap的旋转与镜像水平垂直翻转
-
暴风魔镜Matrix多少钱?暴风魔镜Matrix是什么?
-
POJ3233Matrix Power Series(矩阵快速幂)
-
IE矩阵Matrix滤镜旋转与缩放及如何结合transform
-
python的dataframe和matrix的互换方法
-
numpy matrix和array的乘和加实例
-
20亿豪赌Oculus后 Facebook向Matrix进击
-
PHP+javascript模拟Matrix画面
-
【每日一道算法题】Leetcode之longest-increasing-path-in-a-matrix矩阵中的最长递增路径问题 Java dfs+记忆化