intcur=0; intx=0, y = 0; intd=0; while(cur != m * n){ res.add(matrix[x][y]); vis[x][y] = true; cur++; inttx= x + dx[d]; intty= y + dy[d]; if( tx < 0 || ty < 0 || tx == m || ty == n || vis[tx][ty]){ d = (d + 1) % 4; tx = x + dx[d]; ty = y + dy[d]; } x = tx; y = ty; }