# Java Clean Code

• I hava a simple and easy to understand solution.

``````public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return res;
}
int n = matrix.length;
int m = matrix[0].length;
boolean[][] visited = new boolean[n][m];
int cnt = 1;
int x = 0;
int y = 0;
visited[x][y] = true;
while (cnt < n * m) {
while (cnt < n * m && valid(x, y + 1, visited)) {
y += 1;
visited[x][y] = true;
cnt++;
}
while (cnt < n * m && valid(x + 1, y, visited)) {
x += 1;
visited[x][y] = true;
cnt++;
}
while (cnt < n * m && valid(x, y - 1, visited)) {
y -= 1;
visited[x][y] = true;
cnt++;
}
while (cnt < n * m && valid(x - 1, y, visited)) {
x -= 1;
visited[x][y] = true;
cnt++;
}
}
return res;
}
public boolean valid(int x, int y, boolean[][] visited) {
if (x < 0 || x >= visited.length) {
return false;
}
if (y < 0 || y >= visited[0].length) {
return false;
}
return !visited[x][y];
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.