Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- maze = [[0,0], [0,0]], start = [0,0], destination = [1,1]
- **/
- class Solution {
- fun hasPath(maze: Array<IntArray>, start: IntArray, destination: IntArray): Boolean {
- val startNode = createGraph(maze, Node.Id(row = start[0], col = start[1]))
- val destination: Node? = findDestination(startNode, Node.Id(row = destination[0], col = destination[1]))
- return destination != null
- }
- private fun findDestination(root: Node, destinationId: Node.Id): Node? {
- val visited = mutableSetOf<Node.Id>()
- val queue: Queue<Node> = LinkedList()
- queue.offer(root)
- while(queue.isNotEmpty()) {
- val node = queue.poll()
- if(visited.contains(node.id)) continue
- if(node.id == destinationId) return node
- node.nodes.forEach { queue.offer(it) }
- visited.add(node.id)
- }
- return null
- }
- private fun createGraph(maze: Array<IntArray>, rootId: Node.Id): Node {
- val visited = mutableSetOf<Node.Id>()
- val queue: Queue<Node> = LinkedList()
- val root = Node(Node.Id(row = rootId.row, col = rootId.col))
- queue.offer(root)
- while(queue.isNotEmpty()) {
- val node = queue.poll()
- if(visited.contains(node.id)) continue
- node.addNeighboursIfNeed(maze)
- node.nodes.forEach { queue.offer(it) }
- visited.add(node.id)
- }
- return root
- }
- private fun Node.addNeighboursIfNeed(maze: Array<IntArray>) {
- addTopIfNeed(maze)
- addRightIfNeed(maze)
- addBottomIfNeed(maze)
- addLeftIfNeed(maze)
- }
- private fun Node.addTopIfNeed(maze: Array<IntArray>) {
- var row = id.row - 1
- var col = id.col
- while(row >= 0 && maze[row][col] == 0) {
- row--
- }
- row++
- if(row >= 0 && row != id.row) {
- nodes.add(Node(Node.Id(row, col)))
- }
- }
- private fun Node.addRightIfNeed(maze: Array<IntArray>) {
- var row = id.row
- var col = id.col + 1
- while(col < maze[0].size && maze[row][col] == 0) {
- col++
- }
- col--
- if(col < maze[0].size && col != id.col) {
- nodes.add(Node(Node.Id(row, col)))
- }
- }
- private fun Node.addBottomIfNeed(maze: Array<IntArray>) {
- var row = id.row + 1
- var col = id.col
- while(row < maze.size && maze[row][col] == 0) {
- row++
- }
- row--
- if(row < maze.size && row != id.row) {
- nodes.add(Node(Node.Id(row, col)))
- }
- }
- private fun Node.addLeftIfNeed(maze: Array<IntArray>) {
- var row = id.row
- var col = id.col - 1
- while(col >= 0 && maze[row][col] == 0) {
- col--
- }
- col++
- if(col >= 0 && col != id.col) {
- nodes.add(Node(Node.Id(row, col)))
- }
- }
- data class Node(
- val id: Id,
- val nodes: MutableList<Node> = mutableListOf<Node>()
- ) {
- data class Id(
- val row: Int,
- val col: Int
- )
- }
- }
Add Comment
Please, Sign In to add comment