From 832b75721a0924c89da7b8b0e6972422fbc0a632 Mon Sep 17 00:00:00 2001 From: yuanguangxin <274841922@qq.com> Date: Tue, 4 Feb 2020 02:15:59 +0800 Subject: [PATCH] add q54 --- .idea/workspace.xml | 62 +++++++++++++++++-------------------- src/q54/Solution.java | 72 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 34 deletions(-) create mode 100644 src/q54/Solution.java diff --git a/.idea/workspace.xml b/.idea/workspace.xml index b0a3f28..fe17389 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,8 +2,7 @@ - - + - + - - - + - @@ -225,7 +211,7 @@ - + 1580045439607 @@ -283,7 +269,14 @@ - @@ -298,40 +291,41 @@ - - + - + - + - + - + - + - + - + - + - + @@ -357,10 +351,10 @@ - + - + diff --git a/src/q54/Solution.java b/src/q54/Solution.java new file mode 100644 index 0000000..ebfd055 --- /dev/null +++ b/src/q54/Solution.java @@ -0,0 +1,72 @@ +package q54; + +import java.util.ArrayList; +import java.util.List; + +/** + * 方向变量模拟路径 o(n) + */ +public class Solution { + + public List spiralOrder(int[][] matrix) { + List rs = new ArrayList<>(); + if (matrix.length == 0 || matrix[0].length == 0) { + return rs; + } + int m = matrix.length; + int n = matrix[0].length; + boolean[][] visited = new boolean[m][n]; + + int i = 0; + int j = 0; + int direction = 1; + while (true) { + if (i < 0 || j < 0 || i == m || j == n || visited[i][j]) { + break; + } + rs.add(matrix[i][j]); + visited[i][j] = true; + switch (direction) { + case 1: + if (j + 1 == n || visited[i][j + 1]) { + i++; + direction = 2; + } else { + j++; + } + break; + case 2: + if (i + 1 == m || visited[i + 1][j]) { + j--; + direction = 3; + } else { + i++; + } + break; + case 3: + if (j == 0 || visited[i][j - 1]) { + i--; + direction = 4; + } else { + j--; + } + break; + case 4: + if (visited[i - 1][j]) { + j++; + direction = 1; + } else { + i--; + } + break; + default: + break; + } + } + return rs; + } + + public static void main(String[] args) { + System.out.println(new Solution().spiralOrder(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}})); + } +}