
| class Solution { |
| public int maxDistance(int[][] grid) { |
| |
| |
| |
| |
| int m = grid.length; |
| int n = grid[0].length; |
| boolean[][] visited = new boolean[m][n]; |
| int[][] queue = new int[m * n][2]; |
| int l = 0; |
| int r = 0; |
| int cnt_0 = 0; |
| |
| for (int i = 0; i < m; i++) { |
| for (int j = 0; j < n; j++) { |
| if (grid[i][j] == 1) { |
| queue[r][0] = i; |
| queue[r++][1] = j; |
| visited[i][j] = true; |
| } else { |
| cnt_0++; |
| } |
| } |
| } |
| |
| if (cnt_0 == 0 || cnt_0 == n * m) { |
| |
| return -1; |
| } |
| |
| int ans = 0; |
| int[] next = new int[] { -1, 0, 1, 0, -1 }; |
| |
| while (l != r) { |
| int cur_level = r - l; |
| ans++; |
| for (int k = 0; k < cur_level; k++) { |
| int i = queue[l][0]; |
| int j = queue[l++][1]; |
| |
| |
| for (int g = 0; g < 4; g++) { |
| int next_i = i + next[g]; |
| int next_j = j + next[g + 1]; |
| if (next_i >= 0 && next_i < m && next_j >= 0 && next_j < n && !visited[next_i][next_j]) { |
| queue[r][0] = next_i; |
| queue[r++][1] = next_j; |
| visited[next_i][next_j] = true; |
| } |
| } |
| } |
| } |
| return ans - 1; |
| |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统