# 2061. Number of Spaces Cleaning Robot Cleaned ###### tags: `Leetcode` `Medium` `Microsoft` Link: https://leetcode.com/problems/number-of-spaces-cleaning-robot-cleaned/ ## 思路 just define a direction array and let the robot traverse on the 2D matrix as long as it can until it came back to the visited box at the same direction after trying at most 5 times (in case it got stuck at the starting point, the 5th time will let it go back to it with the original heading direction). ## Code ```java= class Solution { public int numberOfCleanRooms(int[][] room) { int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}}; Map<Integer, Integer> map = new HashMap<>(); int x = 0, y = 0, d = 0, count = 0; map.put(0,0); int cleanRooms = 1; while(true){ for(int k = d;k < d+5;k++){ int nextX = x+directions[k%4][0]; int nextY = y+directions[k%4][1]; if(nextX<0 || nextX>=room.length || nextY<0 || nextY>=room[0].length || room[nextX][nextY]==1) continue; int idx = nextX*room.length+nextY; if(map.containsKey(idx) && map.get(idx)==k%4) return cleanRooms; x = nextX; y = nextY; d = k%4; if(!map.containsKey(idx)) cleanRooms++; map.put(idx, d); break; } if(x==0&&y==0&&d==0) return cleanRooms; } } } ```