Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int finalPositionOfSnake(int n, List<String> commands) {
- int number = 0;
- for (String command : commands) {
- if (command.equals("UP")) {
- number -= n;
- } else if (command.equals("DOWN")) {
- number += n;
- } else if (command.equals("RIGHT")) {
- number++;
- } else if (command.equals("LEFT")) {
- number--;
- }
- }
- return number;
- // row = 0, col = 0..2 => indices 0..2 (indices start from 3 * row = 3 * 0 = 0)
- // row = 1, col = 0..2 => indices 3..5 (indices start from 3 * row = 3 * 0 = 0)
- // row = 2, col = 0..2 => indices 6..8 (indices start from 3 * row = 3 * 0 = 0)
- // row = 0, col = 0..n-1 => indices 0 .. n-1
- // row = 1, col = 0..n-1 => indices n .. 2n-1
- // row = 2, col = 0..n-1 => indices 2n .. 3n-1
- // ...
- // row = n-1, col = 0..n-1 => indices (n-1)*n .. (n*n)-1
- // 0-th row, 0-th col => 0
- // 0-th row, 1-st col => 1
- // 0-th row, 2-nd col => 2
- // 0-th row, 3-rd col => 3
- // ...
- // 0-th row, (n - 1)-th col => n - 1
- // 1-st row, 0-th col => n
- // 1-st row, 1-st col => n + 1
- // 1-st row, 2-nd col => n + 2
- // 1-st row, 3-rd col => n + 3
- // ...
- // 1-st row, (n - 1)-th col => 2 * n - 1
- // ...
- // (n - 1)-th row, 0-th col => (n - 1) * n
- // (n - 1)-th row, 1-st col => (n - 1) * n + 1
- // ...
- // (n - 1)-th row, (n - 1)-th col => n * n - 1
- }
- }
- class Solution {
- public int finalPositionOfSnake(int n, List<String> commands) {
- int row = 0;
- int col = 0;
- for (String command : commands) {
- if (command.equals("UP")) {
- row--;
- } else if (command.equals("DOWN")) {
- row++;
- } else if (command.equals("RIGHT")) {
- col++;
- } else if (command.equals("LEFT")) {
- col--;
- }
- }
- return row * n + col;
- // row = 0, col = 0..2 => indices 0..2 (indices start from 3 * row = 3 * 0 = 0)
- // row = 1, col = 0..2 => indices 3..5 (indices start from 3 * row = 3 * 0 = 0)
- // row = 2, col = 0..2 => indices 6..8 (indices start from 3 * row = 3 * 0 = 0)
- // row = 0, col = 0..n-1 => indices 0 .. n-1
- // row = 1, col = 0..n-1 => indices n .. 2n-1
- // row = 2, col = 0..n-1 => indices 2n .. 3n-1
- // ...
- // row = n-1, col = 0..n-1 => indices (n-1)*n .. (n*n)-1
- // 0-th row, 0-th col => 0
- // 0-th row, 1-st col => 1
- // 0-th row, 2-nd col => 2
- // 0-th row, 3-rd col => 3
- // ...
- // 0-th row, (n - 1)-th col => n - 1
- // 1-st row, 0-th col => n
- // 1-st row, 1-st col => n + 1
- // 1-st row, 2-nd col => n + 2
- // 1-st row, 3-rd col => n + 3
- // ...
- // 1-st row, (n - 1)-th col => 2 * n - 1
- // ...
- // (n - 1)-th row, 0-th col => (n - 1) * n
- // (n - 1)-th row, 1-st col => (n - 1) * n + 1
- // ...
- // (n - 1)-th row, (n - 1)-th col => n * n - 1
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement