【Lintcode】1479. Can Reach The Endpoint

题目地址:

https://www.lintcode.com/problem/can-reach-the-endpoint/description

给定一个二维矩阵, 1 1 1代表空地, 0 0 0代表障碍物, 9 9 9代表终点。每一步只能走到相邻的格子上去,不能走到障碍物上。问从 ( 0 , 0 ) (0,0) (0,0)出发,是否可以走到数字为 9 9 9的那一格子上。

思路是BFS。可以用单向BFS或者双向BFS都可以。这里就使用单向BFS了。为了记录已访问过的点,我们新开一个class叫做Pair,并重写其equals和hashCode方法,以便于加入哈希表。代码如下:

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;

public class Solution {
    /**
     * @param map: the map
     * @return: can you reach the endpoint
     */
    public boolean reachEndpoint(int[][] map) {
        // Write your code here
        // 判空
        if (map == null || map.length == 0 || map[0].length == 0) {
            return false;
        }
        // 如果出发点就是障碍物,直接返回false
        if (map[0][0] == 0) {
            return false;
        }
        // 如果出发点就是终点,那么显然可以到达,返回true
        if (map[0][0] == 9) {
            return true;
        }
        // 开个数组表示四个方向
        int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
        
        Queue<Pair> queue = new LinkedList<>();
        queue.offer(new Pair(0, 0));
        Set<Pair> visited = new HashSet<>(queue);
        while (!queue.isEmpty()) {
            Pair cur = queue.poll();
            // 向四个方向走一步
            for (int i = 0; i < 4; i++) {
                int x = cur.x + dirs[i][0];
                int y = cur.y + dirs[i][1];
                Pair pair = new Pair(x, y);
                // 如果未出界,且未被访问过,则说明该步可以走,进行下一步逻辑
                if (inBound(map, x, y) && !visited.contains(pair)) {
                	// 如果这一步已经到达终点,则返回true;否则加入queue待访问
                    if (map[x][y] == 9) {
                        return true;
                    } else if (map[x][y] == 1) {
                        queue.offer(pair);
                        visited.add(pair);
                    }
                }
            }
        }
        
        return false;
    }
    
    private boolean inBound(int[][] map, int x, int y) {
        return 0 <= x && x < map.length && 0 <= y && y < map[0].length;
    }
    
    class Pair {
        int x, y;
        
        Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        
        @Override
        public boolean equals(Object o) {
            Pair p = (Pair) o;
            return x == p.x && y == p.y;
        }
        
        @Override
        public int hashCode() {
            int result = x;
            result = 31 * result + y;
            return result;
        }
    }
}

时空复杂度 O ( n ) O(n) O(n) n n n为矩阵的size。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值