LeetCode in Kotlin

1496. Path Crossing

Easy

Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.

Return true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false otherwise.

Example 1:

Input: path = “NES”

Output: false

Explanation: Notice that the path doesn’t cross any point more than once.

Example 2:

Input: path = “NESWW”

Output: true

Explanation: Notice that the path visits the origin twice.

Constraints:

Solution

class Solution {
    fun isPathCrossing(path: String): Boolean {
        val visited = ArrayDeque<Coord>()
        visited.add(Coord(0, 0))
        for (c in path.toCharArray()) {
            val last = visited.last()
            if (c == 'N') {
                val nextStep = Coord(last.x, last.y + 1)
                if (visited.contains(nextStep)) {
                    return true
                }
                visited.add(nextStep)
            } else if (c == 'S') {
                val nextStep = Coord(last.x, last.y - 1)
                if (visited.contains(nextStep)) {
                    return true
                }
                visited.add(nextStep)
            } else if (c == 'E') {
                val nextStep = Coord(last.x - 1, last.y)
                if (visited.contains(nextStep)) {
                    return true
                }
                visited.add(nextStep)
            } else if (c == 'W') {
                val nextStep = Coord(last.x + 1, last.y)
                if (visited.contains(nextStep)) {
                    return true
                }
                visited.add(nextStep)
            }
        }
        return false
    }

    internal data class Coord(var x: Int, var y: Int)
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy