登录
  • #码农类general
  • #工作信息
  • #找工就业
  • #WePay
  • #求职(非面经)

我们‌‌‍‍‌‍‌‌‌‌‍‍‌‍‌‍‍‌‌‍‍‍‌‌‌‍‌‌‍‌‍‍付钱OA

dorothyzheng112
1642
13
前几天做的 我们付钱OA还没有消息 题目是 Array Sum 和currency那道 这题edge case好多 解题关键是。。print出过不了的test case然后修改你的代码。。

没遇到sliding blocks所以附上我这道题的代码吧 不保证全部正确~

[mw_shl_code=java,true]int[][] DIRS = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

public int slidingBlocks(List<List<Integer>> board) {

int n = board.size();

int m = board.get(0).size();

StringBuilder startStr = new StringBuilder();

StringBuilder endStr = new StringBuilder();

for (int i = 0; i < n; i++) {

for (int j = 0; j < m; j++) {

startStr.append((char)('a' + board.get(i).get(j)));

endStr.append((char) ('a' + i * m + j));

}

}

String start = startStr.toString();

String end = endStr.toString();

Queue<String> queue = new LinkedList<>();

Set<String> visited = new HashSet<>();

queue.offer(start);

visited.add(start);

int count = 0;

while (!queue.isEmpty()) {

int size = queue.size();

for (int i = 0; i < size; i++) {

String cur = queue.poll();

if (cur.equals(end)) {

return count;

}

int pos = cur.indexOf('a');

int row = pos / m;

int col = pos % m;

for (int j = 0; j < 4; j++) {

int nextRow = row + DIRS[j][0];

int nextCol = col + DIRS[j][1];

if (nextRow >= 0 && nextRow < n && nextCol >= 0 && nextCol < m) {

char val = (char) ('a' + board.get(nextRow).get(nextCol));

String next = getNext(cur, pos, nextRow, nextCol, m, val);

if (!visited.contains(next)) {

visited.add(next);

queue.offer(next);

}

}

}

}

count++;

}

return -1;

}

private String getNext(String cur, int pos, int nextRow, int nextCol, int m,char val) {

StringBuilder sb = new StringBuilder(cur);

int nextPos = nextRow * m + nextCol;

sb.setCharAt(pos, val);

sb.setCharAt(nextPos, 'a');

return sb.toString();

}[/mw_shl_code]

有用的话求大噶给我加个米
13条回复
热度排序

发表回复